I am using string filter function like:
val strings = List("hi","I","am","here") //this list is a stream of words from Twitter
val mystrings = strings.filter(word => !word.contains("I" || "sam") // I need filter out certain stop words
to filter certain words. But I am getting compilation error saying that - value || is not a member of String. Can anybody tell me where I am going wrong?
The method contains on String takes a String as an argument:
"foo".contains("foo") //True
So, the compiler is trying to interpret "I" || "sam" as a String, since that is the argument to contains. In Scala, this statement would be equivalent to "I".||("sam") (calling the || method on "I"). Since there is no method || on String, this fails to compile.
What you probably meant is !(word.contains("I") || word.contains("sam")). This makes sense, since we are now calling || on the Boolean that is returned by word.contains("I"), and || is a method on Boolean (as documented here). So your whole statement might be:
strings.filter(word => !(word.contains("I") || word.contains("sam"))
Which is also equivalent to:
strings.filter(word => !word.contains("I") && !word.contains("sam"))
If you end up with a lot of phrases to filter, you could also flip it around:
val segments = Set("I", "sam")
strings.filter(word => segments.forall(segment => !word.contains(segment)))
//Equivalent
strings.filter(word => !segments.exists(word.contains))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With