Jake
Jake

Reputation: 4660

Scala: Best way to remove tuples from Seq where one value is None

I wish to filter out None values where they appear in a Seq of tuples. In the code below, I want to replace getOrElse with get. But then how do I remove the tuples where the first value is None ?

Here is my code. I feel it is inelegant.

myFirstMap.map {
  case (key, value) =>
    val tuple = (myLookUpMap.getOrElse(key,MyCaseClass("", None)), value.toString)
    tuple
}.filter(_._1.name.nonEmpty).toIndexedSeq

}

What is the correct way to do this?

NOTE: this method will be called thousands of times on Seq with length 40 to 100, so performance is important

Upvotes: 1

Views: 361

Answers (5)

Ivan Finochenko
Ivan Finochenko

Reputation: 1

You can use flatMap to filter None in collection

myFirstMap.flatMap { case (key, value) => myLookUpMap.get(key).map(entity => (entity, value.toString)) }

Upvotes: 0

Steve Waldman
Steve Waldman

Reputation: 14073

Or how about this approach:

val commonKeys = myFirstMap.keySet().intersect( myLookUpMap.keySet() )
val tupleSeq = commonKeys.map { case ( key, value ) =>
  ( myLookUpMap(key), value.toString )
}.toIndexedSeq

Upvotes: 1

Shrikant
Shrikant

Reputation: 21

myFirstMap.collect { case (k, _) if myFilterMap.contains(k) => myFilterMap(k)}

Upvotes: 2

jwvh
jwvh

Reputation: 51271

It looks like .map() and .flatMap() should do the trick, which is what a for comprehension is all about.

(for {
  (k, v) <- myFirstMap
  mcc    <- myLookUpMap.get(k)
} yield (mcc, v.toString)).toIndexedSeq

Upvotes: 3

Steve Waldman
Steve Waldman

Reputation: 14073

Maybe

myFirstMap.map {
  case (key, value) =>
    myLookUpMap.get(key).map( found => Tuple2( found, value.toString ) )
}.withFilter(_.nonEmpty).map( _.get ).toIndexedSeq

...or more readably...

val mbTuples = myFirstMap.map {
  case (key, value) =>
    myLookUpMap.get(key).map( found => Tuple2( found, value.toString ) )
}
val foundTuples = mbTuples.withFilter(_.nonEmpty).map( _.get )
val tupleSeq = foundTuples.toIndexedSeq

Upvotes: 1

Related Questions