Search code examples
scaladata-structuresscala-collectionsscala-2.10sortedmap

Scala - Sort a Map based on Tuple Values


I am attempting to sort a Map based on Value Tuples

val data = Map("ip-11-254-25-225:9000"  -> (1, 1413669308124L), 
               "ip-11-232-145-172:9000" -> (0, 1413669141265L), 
               "ip-11-232-132-31:9000"  -> (0, 1413669128111L), 
               "ip-11-253-67-184:9000"  -> (0, 1413669134073L), 
               "ip-11-232-142-77:9000"  -> (0, 1413669139043L))

The criteria of sort should be based on both the values in the tuple

I tried

SortedMap[String, (Long,Long)]() ++ data

but with no success.

Can someone please suggest a better way to sort first on tuple._1 and then on tuple._2


Solution

  • In general you can select which element in the tuple has priority in the sorting; consider this

    data.toSeq.sortBy {case (k,(a,b)) => (k,a,b) }
    

    In the case pattern we extract each element of the (nested) tuples. In the expression above we sort by key, then by first element in value tuple and then second. On the other hand, this

    data.toSeq.sortBy {case (k,(a,b)) => (k,b) }
    

    will sort by key and last element in value tuple, and this

    data.toSeq.sortBy {case (k,(a,b)) => (a,b) }
    

    by the values of the map; this one

    data.toSeq.sortBy {case (k,(a,b)) => (b) }
    

    will sort by the last element in the values tuple.

    Update As helpfully pointed out by @Paul a Map preserves no ordering, hence the result remains here as a sequence.