Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over all the keys of a map

Is there a way to get a list of all the keys in a Go language map? The number of elements is given by len(), but if I have a map like:

m := map[string]string{ "key1":"val1", "key2":"val2" }; 

How do I iterate over all the keys?

like image 399
Martin Redmond Avatar asked Dec 03 '09 17:12

Martin Redmond


People also ask

How do you get all the keys on a map?

Use keySet() to Get a Set of Keys From a HashMap in Java The simplest way to get the keys from a HashMap in Java is to invoke the keySet() method on your HashMap object. It returns a set containing all the keys from the HashMap .

Can we iterate a map?

Remember that we cannot iterate over map directly using iterators, because Map interface is not the part of Collection. All maps in Java implements Map interface. There are following types of maps in Java: HashMap.


1 Answers

https://play.golang.org/p/JGZ7mN0-U-

for k, v := range m {      fmt.Printf("key[%s] value[%s]\n", k, v) } 

or

for k := range m {     fmt.Printf("key[%s] value[%s]\n", k, m[k]) } 

Go language specs for for statements specifies that the first value is the key, the second variable is the value, but doesn't have to be present.

like image 75
Jonathan Feinberg Avatar answered Sep 20 '22 17:09

Jonathan Feinberg