In Python, you can have key,value pairs in a dictionary where you can loop through them, as shown below:
for k,v in d.iteritems():
print k,v
Is there a way to do this with Java HashMaps?
In Python, you can have key,value pairs in a dictionary where you can loop through them, as shown below:
for k,v in d.iteritems():
print k,v
Is there a way to do this with Java HashMaps?
Yes - for example:
Map<String, String> map = new HashMap<String, String>();
// add entries to the map here
for (Map.Entry<String, String> entry : map.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
System.out.printf("%s %s\n", k, v);
}
The HashMap.entrySet() will return beans of key value pairs similar to the dictionary.iteritems(). You can then loop through them.
I think is the closest thing to the Python version.
As shown in the answers, there are basically two ways to iterate over a Map
(let's assume Map<String, String>
in those examples).
Iterate over Map#entrySet()
:
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
Iterate over Map#keySet()
and then use Map#get()
to get the value for every key:
for (String key : map.keySet()) {
System.out.println(key + "=" + map.get(key));
}
The second one is maybe more readable, but it has a performance cost of unnecessarily calling get()
on every iteration. One may argument that creating the keyset iterator is less expensive because it doesn't need to take values into account. But believe it or not, the keySet().iterator()
creates and uses the same iterator as entrySet().iterator()
. The only difference is that in case of the keySet()
the next()
call of the iterator returns it.next().getKey()
instead of it.next()
.
The AbstractMap#keySet()
's javadoc proves this:
The subclass's iterator method returns a "wrapper object" over this map's
entrySet()
iterator.
The AbstractMap
source code also proves this. Here's an extract of keySet()
method (somewhere around line 300 in Java 1.6):
public Iterator<K> iterator() {
return new Iterator<K>() {
private Iterator<Entry<K,V>> i = entrySet().iterator(); // <-----
public boolean hasNext() {
return i.hasNext();
}
public K next() {
return i.next().getKey(); // <-----
}
public void remove() {
i.remove();
}
};
}
Note that readability should be preferred over premature optimization, but it's important to have this in mind.
Set<Map.Entry> set = d.entrySet();
for(Map.Entry i : set){
System.out.println(i.getKey().toString() + i.getValue().toString);
}
Something like that...
In Java, you can do the same like the following.
HashMap<String, String> h = new HashMap<String, String>();
h.put("1","one");
h.put("2","two");
h.put("3","three");
for(String key:h.keySet()){
System.out.println("Key: "+ key + " Value: " + h.get(key));
}
get()
has an extra cost on every iteration. It's at least not the "right" way to loop through a map. I can imagine that one downvoted because of that, how good your intent also is. –
Charity private Iterator<Entry<K,V>> i = entrySet().iterator(); public K next() { return i.next().getKey(); }
–
Charity You can also use one liner using method references as in below example
Map<String, Object> dict=new TreeMap<String, Object>();
dict.put("age", 20);
dict.put("height", 1.75);
dict.put("country", "India");
dict.put("profession", "developer");
dict.entrySet().stream().forEach(System.out::println);
Output will be
age=20
country=India
height=1.75
profession=developer
© 2022 - 2024 — McMap. All rights reserved.