Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine filter and map in Scala?

I have List[Int] in Scala. The List is List(1,2,3,4,5,6,7,8,9,10). I want to filter the list so that it only has even numbers. And I want to multiply the numbers with 2.

Is it possible?

like image 542
odbhut.shei.chhele Avatar asked Aug 26 '15 18:08

odbhut.shei.chhele


People also ask

Can we use filter and map together?

JavaScript's Array#map() and Array#filter() functions are great when used together because they allow you to compose simple functions. For example, here's a basic use case for filter() : filtering out all numbers that are less than 100 from a numeric array. This function works fine on an array of numbers.

What does map () do in Scala?

map() method is a member of TraversableLike trait, it is used to run a predicate method on each elements of a collection. It returns a new collection.

Is Scala map a HashMap?

HashMap is a part of Scala Collection's. It is used to store element and return a map. A HashMap is a combination of key and value pairs which are stored using a Hash Table data structure. It provides the basic implementation of Map.

What is the use of filter method in Scala?

The filter() method is utilized to select all elements of the list which satisfies a stated predicate. Return Type: It returns a new list consisting all the elements of the list which satisfies the given predicate. Here, an empty list is returned as none of the elements satisfy the stated predicate.


2 Answers

As I state in my comment, collect should do what you want:

list.collect{   case x if x % 2 == 0 => x*2 } 

The collect method allows you to both specify a criteria on the matching elements (filter) and modify the values that match (map)

And as @TravisBrown suggested, you can use flatMap as well, especially in situations where the condition is more complex and not suitable as a guard condition. Something like this for your example:

list.flatMap{   case x if x % 2 == 0 => Some(x*2)   case x => None } 
like image 66
cmbaxter Avatar answered Sep 21 '22 15:09

cmbaxter


A for comprehension (which internally unfolds into a combination of map and withFilter) as follows,

for (x <- xs if x % 2 == 0) yield x*2 

Namely

xs.withFilter(x => x % 2 == 0).map(x => x*2) 
like image 24
elm Avatar answered Sep 21 '22 15:09

elm