Dave's Brain

Browse - Programming Tips - How can I sort the keys of a Map ?

Date: 2012dec16
Language: Scala

Q.  How can I sort the keys of a Map ?

A.  Use keySet to obtain the keys.  But its a Set which aren't sorted.
So convert it to an Array or List and sort with "sorted".

val mymap = Map("one" -> 1, "two" -> 2, "three" -> 3) for (mykey <- mymap.keySet.toArray.sorted) { // Do something }

Add a comment

Sign in to add a comment
Copyright © 2008-2018, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.