Associative Maps

Suppose we want to attach the feed author’s name to feeds; we can store it as a key-value pair in a Map:

 
val​ feeds = Map(​"Andy Hunt"​ -> ​"blog.toolshed.com"​,
 
"Dave Thomas"​ -> ​"pragdave.me"​,
 
"NFJS"​ -> ​"nofluffjuststuff.com/blog"​)

If we want to get a Map of feeds for folks whose name starts with “D,” we can use the filterKeys method:

 
val​ filterNameStartWithD = feeds filterKeys( _ startsWith ​"D"​ )
 
println(s​"# of Filtered: ${filterNameStartWithD.size}"​)

Here’s the result:

 
# of Filtered: 1

On the other hand, if we want to filter on the values, in addition to or instead of the keys, we can use the filter method. The function value we provide to filter receives a (key, value) tuple, and we can use it as ...

Get Pragmatic Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.