List(1, 2) ) migrated to this list of maps, mainly using ...">

How to transfer a map with list values ​​to Scala

Like this list card,

Map ( "a" -> List(1, 2) ) 

migrated to this list of maps, mainly using methods from the Scala libraries?

 List( Map("a" -> 1), Map("a" -> 2) ) 

I can write a solution myself, but I'm more interested in using library functions, so the preferred solution is to use the Scala library, where possible, while remaining compact and moderately legible.

This second example illustrates the required conversion with a map with more than one entry.

From here

 Map ( 10 -> List("10a", "10b", "10c"), 29 -> List("29a", "29b", "29c") ) 

 List( Map( 10 -> "10a", 29 -> "29a"), Map( 10 -> "10b", 29 -> "29b"), Map( 10 -> "10c", 29 -> "29c") ) 

It can be assumed that all values ​​are lists of the same size.

If desired, the solution can handle the case when the values ​​are empty lists, but this is not required. If the solution supports empty list values, then this input,

 Map ( "a" -> List() ) 

should get List() .

+6
source share
1 answer
 val m = Map ( 10 -> List("10a", "10b", "10c"), 29 -> List("29a", "29b", "29c") ) m.map{ case (k, vs) => vs.map(k -> _) }.toList.transpose.map(_.toMap) 

Please note that this also handles your "empty list" case.

+9
source

Source: https://habr.com/ru/post/950239/


All Articles