How do I concatenate lists that are map values?

Given:

scala> var a = Map.empty[String, List[Int]]
a: scala.collection.immutable.Map[String,List[Int]] = Map()

scala> a += ("AAA" -> List[Int](1,3,4))

scala> a += ("BBB" -> List[Int](4,1,4))

scala> a
res0: scala.collection.immutable.Map[String,List[Int]] = Map(AAA -> List(1, 3, 4), BBB -> List(4, 1, 4))

      

How can I combine the values ​​into one iterative collection (for sorting)?

List(1, 3, 4, 4, 1, 4)

      

How do I end this code?

a.values.[???].sorted

      

+3


source to share


4 answers


Consider

a.flatMap(_._2)

      

which aligns the second element of each tuple (each value in the map).



Equivalent in this case also

a.values.flatMap(identity)

      

+5


source


You must end:

a.values.flatten

      

Result:

scala> Map("AAA" -> List(1, 3, 4), "BBB" -> List(4, 1, 4))
res50: scala.collection.immutable.Map[String,List[Int]] = Map(AAA -> List(1, 3, 4), BBB -> List(4, 1, 4))

scala> res50.values.flatten
res51: Iterable[Int] = List(1, 3, 4, 4, 1, 4)

      



Updated:

For your specific case, these are:

(for(vs <- a.asScala.values; v <- vs.asScala) yield v.asInstanceOf[TargetType]).sorted

      

+8


source


This will work

 a.values.flatten                              
//> res0: Iterable[Int] = List(1, 3, 4, 4, 1, 4)

      

+7


source


My assessment of all the responses I received. Finally, good points led to some really working code. Below is a real snippet of code and x

here org.apache.hadoop.hbase.client.Put

that does everything "the hell in the details". I need HBase to Put

convert to a list of matching data cells (accessible from puts via an interface org.apache.hadoop.hbase.Cell

), but I need to expose the fact that they are indeed implemented as KeyValue

( org.apache.hadoop.hbase.KeyValue

).

val a : Put ...

a.getFamilyCellMap.asScala
    .flatMap(
        _._2.asScala.flatMap(
            x => List[KeyValue](x.asInstanceOf[KeyValue]) )
    ).toList.sorted

      

Why is it so difficult?

  • Put is a Java type for representing the contents of a "write" operation, and we can only get its cells through a map of family cells whose elements are lists. Of course they are all Java.
  • I only have access to interface ( Cell

    ), but I need implementation ( KeyValue

    ), so a conversion is required. I have a guarantee that there is nothing else.

The funny thing is that after all this, I decided to drop the standard Put

and encapsulate the data in another container (which is my regular class) at an earlier stage, and that made things a lot easier.

So a more general answer for this case, where a java.util.Map[?]

with values java.util.List[?]

and list items, has BaseType

, but you need "TargetType" is probably:

a.asScala.flatMap(
    _._2.asScala.flatMap(
        x => List[TargetType](x.asInstanceOf[TargetType]) )
).toList.sorted

      

+1


source







All Articles