C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Keys: We get the keys from the map by using "range" and appending to an empty slice with append().
Values: Next we get the values from the map with range. We ignore the key in each iteration as we do not need it.
Pairs: Suppose we want a slice of 2-element string arrays. We can create these in a slice of pairs.
Flat: Here we place all the keys and values one after another in a flattened slice. This is easy to loop over.
Golang program that converts map to slices
package main
import "fmt"
func main() {
// Create example map.
m := map[string]string{
"java": "coffee",
"go": "verb",
"ruby": "gemstone",
}
// Convert map to slice of keys.
keys := []string{}
for key, _ := range m {
keys = append(keys, key)
}
// Convert map to slice of values.
values := []string{}
for _, value := range m {
values = append(values, value)
}
// Convert map to slice of key-value pairs.
pairs := [][]string{}
for key, value := range m {
pairs = append(pairs, []string{key, value})
}
// Convert map to flattened slice of keys and values.
flat := []string{}
for key, value := range m {
flat = append(flat, key)
flat = append(flat, value)
}
// Print the results.
fmt.Println("MAP ", m)
fmt.Println("KEYS SLICE ", keys)
fmt.Println("VALUES SLICE", values)
fmt.Println("PAIRS SLICE ", pairs)
fmt.Println("FLAT SLICE ", flat)
}
Output
MAP map[go:verb ruby:gemstone java:coffee]
KEYS SLICE [java go ruby]
VALUES SLICE [verb gemstone coffee]
PAIRS SLICE [[ruby gemstone] [java coffee] [go verb]]
FLAT SLICE [java coffee go verb ruby gemstone]