Rocky Pulley
Rocky Pulley

Reputation: 23321

How do I filter a list with functional programming in scala?

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?

Upvotes: 0

Views: 137

Answers (2)

cmbaxter
cmbaxter

Reputation: 35463

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

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

Upvotes: 3

om-nom-nom
om-nom-nom

Reputation: 62855

Almost literal representation of your requirement definition:

val list2 = list1.filterNot(item => item.contains('a'))
// List[String] = List(dsf, rewgds, werwe)

Upvotes: 5

Related Questions