undisp
undisp

Reputation: 721

Compare two lists in Scala

I have a List[(String, Int)] and a List[String].

The first one contains the number of occurrences of a word in a string, for example:

"This is a sample string like every other sample string"

The list List[(String, Int)] is:

List(("This", 1), ("is", 1), ("a", 1), ("sample", 2), ("string", 2), ...)

The second list contains multiple strings, let's say that it contains:

List("one", "two", "string", "is")

Comparing the two strings I want to get the following:

Result = 3

Because the second list contains "string" and "is" and the list string contains two "string" and one "is". So 2+1=3.

Does anyone know a way to compare both lists and get this result?

Upvotes: 1

Views: 12173

Answers (3)

RAGHHURAAMM
RAGHHURAAMM

Reputation: 1099

Try this: Even if you change your input string dynamically it works fine even by calculating itself the counts of each word in the input string.

list1.distinct.map(x=>(x,list1.count(_==x))).filter(x=>list2.contains(x._1)).unzip._2.sum

or if you want to use input string 's' directly use this:

s.split(" +").distinct.map(x=>(x,list1.count(_==x))).filter(x=>list2.contains(x._1)).unzip._2.sum

for

val s = "This is a sample string like every other sample string"
scala> val list1= s.split(" +")
list1: Array[String] = Array(This, is, a, sample, string, like, every, other, sample, string)

list2 = val list2 = List("one", "two", "string", "is")

In SCALA REPL:

scala> list1.distinct.map(x=>(x,list1.count(_==x))).filter(x=>list2.contains(x._1)).unzip._2.sum
res157: Int = 3

scala>

Upvotes: 0

Regis Blanc
Regis Blanc

Reputation: 549

You can use foldLeft:

val l1: List[(String, Int)] = ???
val l2: List[String] = ???

l1.foldLeft(0)((acc, p) => if(l2.contains(p._1)) acc+p._2 else acc)

If you need to optimize it, you can first transforming the l2 to a Set, and then the contains should be mostly O(1) instead of linear.

Upvotes: 2

Dogbert
Dogbert

Reputation: 222040

I'd suggest converting the occurrences list to a Map and then run a .map(..).sum over the second list:

scala> val occurrences = List(("This", 1), ("is", 1), ("a", 1), ("sample", 2), ("string", 2)).toMap
occurrences: scala.collection.immutable.Map[String,Int] = Map(is -> 1, This -> 1, a -> 1, string -> 2, sample -> 2)

scala> val input = List("one", "two", "string", "is")
input: List[String] = List(one, two, string, is)

scala> val answer = input.map(occurrences.getOrElse(_, 0)).sum
answer: Int = 3

Upvotes: 2

Related Questions