Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,8 @@ lazy val scala_strings = (project in file("scala-strings"))
.settings(
name := "scala-strings",
libraryDependencies ++= scalaTestDeps,
libraryDependencies += jUnitInterface
libraryDependencies += jUnitInterface,
libraryDependencies += "org.scala-lang.modules" %% "scala-parallel-collections" % "1.0.4"
)

lazy val scala_design_patterns = (project in file("scala-design-patterns"))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.baeldung.scala.strings.keywordsearch

import scala.collection.parallel.CollectionConverters._
import scala.io.Source

object KeywordCounter extends App {

// Load the text of "Pride and Prejudice" from Project Gutenberg
val url = "https://www.gutenberg.org/files/1342/1342-0.txt"
val text = Source.fromURL(url).mkString

val keywords = List("Darcy", "Bennet", "Pemberley", "Bingley", "Wickham")

// Split the text into words and transform it into a parallel collection
val words = text.split("\\W+").par

// Count occurrences of each keyword
val counts = keywords.par.map { keyword =>
keyword -> words.count(_ == keyword)
}.seq // Convert back to a sequential map for consistent output

counts.foreach { case (keyword, count) =>
println(s"$keyword: $count")
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.baeldung.scala.strings.keywordsearch

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class KeywordMatchingSpec extends AnyFlatSpec with Matchers {

"Keyword Matching" should "detect keywords in a string using brute-force" in {
val text = "May the Force be with you"
val keys = List("Force", "Wakanda", "Hobbit")

val words = text.split(" ")
var containsKeyword = false

for (word <- words) {
for (key <- keys) {
if (word == key) {
containsKeyword = true
}
}
}

assert(containsKeyword)
}

it should "detect keywords using Scala's built-in methods" in {
val text = "May the Force be with you"
val keys = List("Force", "Wakanda", "Hobbit")

val containsKeyword = keys.exists(key => text.split(" ").contains(key))
assert(containsKeyword)
}

it should "optimize keyword detection using Scala collections" in {
val text = "May the Force be with you"
val keys = List("Force", "Wakanda", "Hobbit").toSet

val words = text.split(" ").toSet
val containsKeyword = keys.exists(key => words.contains(key))

assert(containsKeyword)
}

// Add other tests as needed
}