LeBaguette
LeBaguette

Reputation: 11

How do I sort a list of maps by a value in the maps? (Scala)

I'm new to Scala. I currently have a list of maps where each map maps a list of doubles to a double: List[Map[List[Double],Double]]. Each map only has 1 entry and the amount of maps inside the list is randomly generated and so are the rest of the numbers. I am trying to order a list of these maps by the value of the maps from least to greatest. I've tried using sortWith but I don't think that is the right approach. Can anyone please help me with this?

val currentList = List(
    Map(List(1,2,2) -> 7.0),
    Map(List(4,7,1) -> 3.6),
    Map(List(1,9,1) -> 7.7),
    Map(List(4,1,0) -> 12.4),
    Map(List(3,6,8) -> 5.2),
    Map(List(9,2,7) -> 6.1)
  )

  val desiredList = List(
    Map(List(4,7,1) -> 3.6),
    Map(List(3,6,8) -> 5.2),
    Map(List(9,2,7) -> 6.1),
    Map(List(1,2,2) -> 7.0),
    Map(List(1,9,1) -> 7.7),
    Map(List(4,1,0) -> 12.4)
  )```

Upvotes: 0

Views: 350

Answers (2)

jwvh
jwvh

Reputation: 51271

sortBy() also works.

currentList.sortBy(_.values.headOption)
//res0: List[Map[List[Int],Double]] = List(
//    Map(List(4, 7, 1) -> 3.6)
//  , Map(List(3, 6, 8) -> 5.2)
//  , Map(List(9, 2, 7) -> 6.1)
//  , Map(List(1, 2, 2) -> 7.0)
//  , Map(List(1, 9, 1) -> 7.7)
//  , Map(List(4, 1, 0) -> 12.4))

This is also easier and safer if the List contains an empty Map() because sortBy() will sort Options, putting None before any Some(..).

Upvotes: 3

jf_
jf_

Reputation: 3479

It is indeed possible using sortWith, where you can use a lambda expression as the comparator for the sort. I assume you meant sorting by values instead of keys, and that there is always one entry in the map.

val desiredList = currentList.sortWith((one, two) => one.values.head < two.values.head)

Upvotes: 0

Related Questions