Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate lists that are values of map?

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 to concatenate the values to a single iterable collection (to be sorted)?

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

How should I end this code?

a.values.[???].sorted
like image 491
Roman Nikitchenko Avatar asked Nov 29 '22 10:11

Roman Nikitchenko


1 Answers

You should end it with:

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 it's:

(for(vs <- a.asScala.values; v <- vs.asScala) yield v.asInstanceOf[TargetType]).sorted
like image 187
dk14 Avatar answered Dec 05 '22 14:12

dk14