SoFunction
Updated on 2025-03-05

Example of method of sorting Map by Value size in Golang

The map in Golang defaults to unordered .

cause

There is a requirement in recent projects:

Based on the user's current coordinate point, get the preset city name near the user.

There is a point of note here that assuming that these supported city names are preset, you cannot directly obtain the city name based on coordinate points through the map class API.

The solution that came up is:

  1. Get the coordinate points of these preset cities
  2. Get the user's current coordinate point on the App side
  3. The coordinate point distance between the user's coordinate point from each preset city is calculated separately
  4. Then calculate the smallest distance item
  5. The corresponding city of this coordinate point is what you want

explore

After the preliminary calculation, after step 3 above, I got the following result:

result := map[string]float64{  
"City A": 2334.20,
"City B": 1992.33,
"City C": 500.26,
"City D": 10.39,
"City E": 333.33,
}

We know that Map in Golang is disordered. So when we use for-range loop:

for k, v := range result {  
   ("key: %v value: %v \n", k, v)  
}

The result may be:

// The first possible result:
key: City B value: 1992.33
key: City C value: 500.26
key: City D value: 10.39
key: City E value: 333.33
key: City A value: 2334.2

// The second possible result:
key: City E value: 333.33
key: City A value: 2334.2
key: City B value: 1992.33
key: City C value: 500.26
key: City D value: 10.39

// The third possible result:
key: City E value: 333.33
key: City A value: 2334.2
key: City B value: 1992.33
key: City C value: 500.26
key: City D value: 10.39

So, we cannot sort by key or value.

accomplish

But the slices in Golang are ordered. We can use Slice to sort Map in the result.

first step

Let's first convert the map above to a slice:

type KVPair struct {  
   Key string  
 Val float64  
}  
  
tmpList := make([]KVPair, 0)  
  
for k, v := range result {  
   tmpList = append(tmpList, KVPair{Key: k, Val: v})  
}

A structure slice is created above and then the value of map is added to the slice.

Step 2

After go1.8, the () method was introduced to sort slices. We only need to pass in a comparison function:

(tmpList, func(i, j int) bool {  
   return tmpList[i].Val < tmpList[j].Val // Ascending order})

Step 3

Then, we perform a for-range traversal on the sorted slice:

for _, pair := range tmpList {  
   ("key: %v value: %v \n", , )  
}

// result:key: CityD value: 10.39 
key: CityE value: 333.33 
key: CityC value: 500.26 
key: CityB value: 1992.33 
key: CityA value: 2334.2

As you can see, the first item of the sorted slice is the result we want.

If we want to get the item with the largest value, we just need to change the comparison method interface in:

(tmpList, func(i, j int) bool {  
   return tmpList[i].Val &gt; tmpList[j].Val // descending order //return tmpList[i].Val < tmpList[j].Val // ascending })

Summarize

The complete code of the above test is as follows:

package main  
  
import (  
   "fmt"  
 "sort")  
  
var result = map[string]float64{  
   "City A": 2334.20,  
 "City B": 1992.33,  
 "City C": 500.26,  
 "City D": 10.39,  
 "City E": 333.33,  
}

func main() {

   type KVPair struct {  
      Key string  
      Val float64  
   }  
  
   tmpList := make([]KVPair, 0)  
  
   for k, v := range result {  
      tmpList = append(tmpList, KVPair{Key: k, Val: v})  
   }  
  
   (tmpList, func(i, j int) bool {  
      //return tmpList[i].Val > tmpList[j].Val // descending      return tmpList[i].Val &lt; tmpList[j].Val // Ascending order   })  
  
   for _, pair := range tmpList {  
      ("key: %v value: %v \n", , )  
   }  
}

Summarize

This is the article about the sorting of Map in Golang by Value size. For more related content in Golang, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!