How to sort key and values in map in Golang 1.20

Channel:
Subscribers:
5,740
Published on ● Video Link: https://www.youtube.com/watch?v=w4BwjzDrHzE



Category:
Tutorial
Duration: 3:02
7 views
0


In this video we are going to generate source code for the GoLang Program, How to sort key and values in map using chatGPT.
After generating we will verify and run the generated code.

IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.



##############SOURCE CODE#########################

package main

import (
"fmt"
"sort"
)

func main() {
// Create a map of string keys and int values
data := map[string]int{
"foo": 3,
"bar": 2,
"baz": 1,
}

// Copy the keys into a slice and sort it
keys := make([]string, len(data))
i := 0
for k := range data {
keys[i] = k
i++
}
sort.Strings(keys)

// Print the map elements in key order
fmt.Println("Sorted by key:")
for _, k := range keys {
fmt.Printf("%s: %d\n", k, data[k])
}

// Copy the values into a slice and sort it
values := make([]int, len(data))
j := 0
for _, v := range data {
values[j] = v
j++
}
sort.Ints(values)

// Print the map elements in value order
fmt.Println("Sorted by value:")
for _, v := range values {
for k, val := range data {
if val == v {
fmt.Printf("%s: %d\n", k, v)
delete(data, k) // remove the printed element
break
}
}
}
}

##############END OF SOURCE CODE#########################

Below is the explanation for the program:

In Go, maps are inherently unordered. However, if you want to sort the keys or values in a map,
you can do so by copying the keys or values into a slice, sorting the slice, and then iterating over the sorted slice to access the map elements.

In this program, we create a map called data with string keys and int values. We then copy the keys and values into slices and sort them using the sort.Strings and sort.Ints functions.

To print the map elements in key order, we iterate over the sorted keys slice and use the key to access the corresponding value in the map.

To print the map elements in value order, we iterate over the sorted values slice and use a nested loop to search for the key that corresponds to each value in the map. When we find a key that matches a value, we print the key-value pair and remove the printed element from the map using the delete function.

When we run this program, we get the following output:

#go #goprogramming #golang #golangtutorial #golanguage







Tags:
how to sort key values in map in golang
go program to sort key value pairs in map
sorting in map in go
sorted map in go
maps in go
go Programming Tutorial
go by example
go Language
go projects
go programming projects
go tutorial
golang tutorial
golang projects
go programming course
learn go
how to run go program
golang videos
golang with chatgpt
coding questions
coding interview questions