0

I have two lists:

val list1 = List("asdf", "fdas", "afswd", "dsf", "twea", "rewgds", "werwe", "dsadfs");
val list2 = List();

I want to filter all items from list1 and setup list2 so that it only contains items that don't contain the letter 'a'. I know how to do this with imperative programming, but how would I do this with functional programing?

2 Answers 2

5

Almost literal representation of your requirement definition:

val list2 = list1.filterNot(item => item.contains('a'))
// List[String] = List(dsf, rewgds, werwe)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I guess what I really need though is to figure out something that doesn't have a default implementation already by Scala. Let's say I have an object and I want to call getId() on each object and then return only the items whose ID contains an 'a' character?
I deleted my post that illustrated this but iterating through would work for any object.
@TritonMan it will be quite the same: xs.filter(obj => obj.getId.contains('a')) (note, filterNot versus filter). One might write the former code as list1.filter(item => !item.contains('a')), but I prefer this filter/filterNot way.
3

In response to your comment on @om-nom-nom's answer:

val list2 = for(item <- list1 if !item.contains("a")) yield item

3 Comments

Just as a side note, both @cmbaxter and mine solutions will be desugared to a nearly the same code.
yeah I think I get that. Also, it looks like maybe I can use _.contains() instead of the "item => item.contains()". Is that the same thing?
@TritonMan yep, it is shorthand syntax

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.