techkuz
techkuz

Reputation: 3956

Map over HashMap and avoid empty results

I have an immutable HashMap:

val hashmap = Seq(1,2,3,3,2).groupBy(identity).map({x => x._1 -> x._2.length})

println(hashmap)
// HashMap(1 -> 1, 2 -> 2, 3 -> 2)

I try to filter it by value (2) and get the keys:

val res = hashmap.map({ case (key, value) => if (value == 2) key})

println(res)
// List((), 2, 3)

However, it returns an empty tuple if there is a key/value pair in hashmap which does not satisfy value==2.

Where do these empty tuples come from? Is there an easy approach how to avoid them?

I want to have a List(2, 3) as a result.

Online code

Upvotes: 1

Views: 227

Answers (2)

Tomer Shetah
Tomer Shetah

Reputation: 8529

Another option you have is:

hashmap.filter(_._2 == 2).keys.toList

Or if you are also fine with Set you can do:

hashmap.filter(_._2 == 2).keySet

Upvotes: 2

Mario Galic
Mario Galic

Reputation: 48410

Omitting else clause

if (value == 2) key

is equivalent to

if (value == 2) key else ()

which is why

hashmap.map({ case (key, value) => if (value == 2) key})

evaluates to

val res0: scala.collection.immutable.Iterable[AnyVal] = List((), 2, 3)

Instead try collect which is semantically equivalent to map+filter like so

hashmap.collect { case (key, value) if value == 2 => key }
// val res2: scala.collection.immutable.Iterable[Int] = List(2, 3)

Upvotes: 5

Related Questions