Wangkkkkkk
Wangkkkkkk

Reputation: 15

Scala-A function about 'contains'

If I want to have a function can be achieved on the screening of certain values.

E.g val strings = List("a", "b", "c", "e", "r")
val SpecificStrings = List("a", "b", "d")

Through the function, I will get the result:

List("a", "b")

So what should I code this function?Thx

Upvotes: 0

Views: 97

Answers (2)

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41957

There are multiple ways to achieve the same result in Scala

Using filter

strings.filter(SpecificStrings.contains(_))
//res0: List[String] = List(a, b)

Using ListBuffer and for loop

val listBuffer = new ListBuffer[String]
for(str <- strings){
  if(SpecificStrings.contains(str)){
    listBuffer += str
  }
}
listBuffer.toList
//res1: List[String] = List(a, b)

There are recursive methods too but recursive methods would require a new stack frame for each recursion and is not suitable for huge datasets.

Upvotes: 2

zhjh1209
zhjh1209

Reputation: 41

Just do it like this:

strings.intersect(SpecificStrings)

Do not write a funciton your self.

Upvotes: 4

Related Questions