O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required