Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way of converting a Map[K, Option[V]] to a Map[K,V]

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?

like image 450
Don Roby Avatar asked Oct 06 '11 20:10

Don Roby


People also ask

Can we convert list to map in Java?

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.

Can we convert map to set?

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.


2 Answers

input.collect{case (k, Some(v)) => (k,v)}
like image 124
Didier Dupont Avatar answered Sep 28 '22 11:09

Didier Dupont


input flatMap {case(k,ov) => ov map {v => (k, v)}}
like image 43
Tomasz Nurkiewicz Avatar answered Sep 28 '22 10:09

Tomasz Nurkiewicz