How to convert List (String, String) to ListMap [String, String]?

I have a list of types List(String,String), and I would like to convert it to a map. When I used the method toMap, I found that it does not preserve the order of the data that is on the list. However, my goal is to convert the list to Map, preserving the data order similar to the list. I found out that it ListMappreserves the insertion order (but it is unchanged), so I can use the LinkedHashMap with the display function to paste the data in sequentially LinkedHashMap, but that means I need to iterate over all the elements that are pain. Can anyone suggest me a better approach? Thanks

+8
source share
2 answers

This should do it:

val listMap = ListMap(list : _*)
+11
source

In Scala> 2.13:

scala> import scala.collection.immutable.ListMap
import scala.collection.immutable.ListMap

scala> val list = List((1,2), (3,4), (5,6), (7,8), (9,0))
list: List[(Int, Int)] = List((1,2), (3,4), (5,6), (7,8), (9,0))

scala> list.to(ListMap)
res3: scala.collection.immutable.ListMap[Int,Int] = ListMap(1 -> 2, 3 -> 4, 5 -> 6, 7 -> 8, 9 -> 0)
0
source

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


All Articles