Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to get the keys in a map in alphabetical order

Tags:

sorting

go

map

In Go, what's the easiest way to get the keys in a map sorted alphabetically? This is the shortest way I can do it:

package main  import "container/vector" import "fmt" import "sort"  func main() {     m := map[string]string {"b":"15", "z":"123123", "x":"sdf", "a":"12"}     var keys vector.StringVector;     for k,_ := range ( m ) {             keys.Push(k)     }     sort.Sort( &keys )     fmt.Printf("%v\n", keys) } 
like image 493
marketer Avatar asked Jan 10 '10 20:01

marketer


People also ask

How do you sort a HashMap by key alphabetically?

Just use a TreeMap . It implements the SortedMap interface, and thus automatically sorts the keys it contains. Your keys can just be sorted alphabetically to get the desired result, so you don't even need to provide a comparator. HashMaps are never sorted.

How do you sort elements in ascending order on a map?

Sort HashMap in Ascending Order. To sort the unsortedMap we've seen earlier, we'll create a new LinkedHashMap to house the elements in the order we want them to be in. Let's start off with sorting a HashMap in ascending order: Map<String, Integer> sortedMap = unsortedMap.

How do you sort values in descending order in HashMap on the basis of key?

In order to sort in decreasing order, just reverse the order of Comparator using Collections. reverseOrder() or Comparator. reverse() method of Java 8.


2 Answers

You are sorting an array of strings using StringVector. To minimize overhead, you could sort an array of strings.

package main  import (     "fmt"     "sort" )  func main() {     m := map[string]string{"b": "15", "z": "123123", "x": "sdf", "a": "12"}     mk := make([]string, len(m))     i := 0     for k, _ := range m {         mk[i] = k         i++     }     sort.Strings(mk)     fmt.Println(mk) } 

Output:

[a b x z] 
like image 83
peterSO Avatar answered Sep 21 '22 00:09

peterSO


That would be most elegant method:

package main  import (     "fmt"     "sort" )  func main() {     m := map[string]string{"b": "15", "z": "123123", "x": "sdf", "a": "12"}     keys := make([]string, 0, len(m))     for key := range m {         keys = append(keys, key)     }     sort.Strings(keys)     fmt.Println(keys) } 
like image 23
Igor Dolzhikov Avatar answered Sep 21 '22 00:09

Igor Dolzhikov