Reputation: 15
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
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
Reputation: 41
Just do it like this:
strings.intersect(SpecificStrings)
Do not write a funciton your self.
Upvotes: 4