tec*_*kuz 1 dictionary functional-programming scala hashmap
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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
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.
Omitting else clause
if (value == 2) key
Run Code Online (Sandbox Code Playgroud)
is equivalent to
if (value == 2) key else ()
Run Code Online (Sandbox Code Playgroud)
which is why
hashmap.map({ case (key, value) => if (value == 2) key})
Run Code Online (Sandbox Code Playgroud)
evaluates to
val res0: scala.collection.immutable.Iterable[AnyVal] = List((), 2, 3)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |