Scala filter method map
![scala filter method map scala filter method map](https://javadeveloperzone.com/wp-content/uploads/2018/08/Java-stream-filter-null-values.jpg)
In an interesting use, you can also use a Set with filterKeys to define the elements to retain: Then pass the method to the filterKeys method: Scala> def only1(i: Int) = if (i = 1) true else false First define your method, such as this method, which returns true when the value the method is given is 1: If your algorithm is longer, you can define a function (or method), and then use it in the filterKeys call, rather than using an anonymous function. The predicate you supply should return true for the elements you want to keep in the new collection and false for the elements you don’t want. When using this method, remember to assign the filtered result to a new variable: When working with a mutable or immutable map, you can use a predicate with the filterKeys methods to define which map elements to retain. Res1: = Map(2 -> B, 3 -> C)ĭepending on your definition of “filter,” you can also remove elements from a map using methods like remove and clear, which are shown in Recipe 11.16. Scala> x.transform((k,v) => v.toUpperCase) In a related note, the transform method doesn’t filter a map, but it lets you transform the elements in a mutable map: Your algorithm can test both the key and value of each element to decide which elements to retain in the map. As implied by the anonymous function signature used in that example: Res1: = Map(2 -> b, 3 -> c)Īs shown, retain modifies a mutable map in place. You can filter the elements in a mutable map using the retain method to specify which elements should be retained: Use the retain method to define the elements to retain when using a mutable map, and use filterKeys or filter to filter the elements in a mutable or immutable map, remembering to assign the result to a new variable. You want to filter the elements contained in a Scala Map, either by directly modifying a mutable map, or by applying a filtering algorithm on an immutable map to create a new map. This is Recipe 11.22, “How to Filter a Scala Map” Problem This is an excerpt from the Scala Cookbook (partially modified for the internet). show more info on classes/objects in repl.