-1

I'm new to golang and I'd like to invert the order of appearance of pairs in a map like this so that the last pair comes first:

mapA := map[string]int {
    "cat": 5,
    "dog": 2,
    "fish": 3 ,
}


fmt.Println(mapA)


map[cat:5 dog:2 fish:3]

The resulting map should be like:

map[fish:3 dog:2 cat:5]

It can be a new mapB with the same items but iverted order.

How can I achieve this?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Babr
  • 1,971
  • 14
  • 33
  • 47

1 Answers1

7

The Go Programming Language Specification

Map types

A map is an unordered group of elements.

For statements

The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.


You can't. A Go map is not ordered. A Go map is a hash map (hash table).

To get the map contents in order (or reverse order), read the map contents into a slice and sort it.


Hash table - Wikipedia

A hash table uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found.

Drawbacks

The entries stored in a hash table can be enumerated efficiently (at constant cost per entry), but only in some pseudo-random order. Therefore, there is no efficient way to locate an entry whose key is nearest to a given key. Listing all n entries in some specific order generally requires a separate sorting step, whose cost is proportional to log(n) per entry.

peterSO
  • 158,998
  • 31
  • 281
  • 276