Search code examples
pythonscalasortingdictionary

scala map get keys from Map as Sequence sorting by both keys and values


In Python I can do:

in_dd = {"aaa": 1, "bbb": 7, "zzz": 3, "hhh": 9, "ggg": 10, "ccc": 3}
out_ll = ['ggg', 'hhh', 'bbb', 'aaa', 'ccc', 'zzz']

so, I want to get keys sorted by value in descending order while having keys in ascending order taking into consideration sorted values

How can I do it in Scala?

In Scala I know I can do:

val m = Map("aaa" -> 3, "bbb" -> 7, "zzz" -> 3, "hhh" -> 9, "ggg" -> 10, "ccc" -> 3)
m.toSeq.sortWith(_._2 > _._2)

but I do not know how to sort by two cases.

EDIT:

I have tried also such approach but it does not return desired result:

m.toSeq.sortWith((x,y) => x._2 > y._2 && x._1 < y._1).map(_.1)
List((ggg,10), (hhh,9), (bbb,7), (ccc,3), (zzz,3), (aaa,3))

notice it shall be aaa,ccc,zzz


Solution

  • In scala you could use:

    m.toSeq.sortBy(a => (a._2, a._1) )(Ordering.Tuple2(Ordering.Int.reverse, Ordering.String.reverse))
    

    for List((ggg,10), (hhh,9), (bbb,7), (zzz,3), (ccc,3), (aaa,3))

    and

    m.toSeq.sortBy(a => (-a._2, a._1) )
    

    for List((ggg,10), (hhh,9), (bbb,7), (aaa,3), (ccc,3), (zzz,3))