How to reorder a List containing Maps based on Key

2019-08-26 06:25发布

问题:

How to reorder

List(Map(d -> 4, a -> 1, c -> 3, b -> 2), Map(d -> 8, a -> 2, c -> 6, b -> 4))

to

List(Map(a -> 1, b -> 2, c -> 3, d -> 4), Map(a -> 2, b -> 4, c -> 6, d -> 8))

using Scala?

回答1:

import scala.collection.immutable.SortedMap

val a = Map('d' -> 4, 'a' -> 1, 'c' -> 3, 'b' -> 2)
val b = Map('d' -> 8, 'a' -> 2, 'c' -> 6, 'b' -> 4)

val c = List(a, b)

val d = c.map(SortedMap[Char, Int]() ++ _)

You can map over the contents of c and create a new SortedMap from the contents of each map.



标签: scala