I have some code that is producing a Map
where the values are Option
types, and I really of course want a map containing only the real values.
So I need to convert this, and what I've come up with in code is
def toMap[K,V](input: Map[K, Option[V]]): Map[K, V] = {
var result: Map[K, V] = Map()
input.foreach({
s: Tuple2[K, Option[V]] => {
s match {
case (key, Some(value)) => {
result += ((key, value))
}
case _ => {
// Don't add the None values
}
}
}
})
result
}
which works, but seems inelegant. I suspect there's something for this built into the collections library that I'm missing.
Is there something built in, or a more idiomatic way to accomplish this?
With Java 8, you can convert a List to Map in one line using the stream() and Collectors. toMap() utility methods. The Collectors. toMap() method collects a stream as a Map and uses its arguments to decide what key/value to use.
To convert, Java Map to Set , we can use the conventional constructor with HashSet , however, there are few things to consider before we proceed with the conversion.
input.collect{case (k, Some(v)) => (k,v)}
input flatMap {case(k,ov) => ov map {v => (k, v)}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With