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?
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.
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.
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.
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.
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 }
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)
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