Organizational Research By

Surprising Reserch Topic

how to Iterate through a HashMap in java?


What's the best way to iterate over the items in a HashMap?

asked Jun 19, 2015 in Core java by rajesh
0 votes
102 views



Related Hot Questions

3 Answers

0 votes
Iterate through the entrySet like so:

public static void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
        it.remove(); // avoids a ConcurrentModificationException
    }
}
answered Jun 19, 2015 by rajesh
0 votes
If you're only interested in the keys, you can iterate through the keySet() of the map:

Map map = ...;

for (String key : map.keySet()) {
    // ...
}
If you only need the values, use values():

for (Object value : map.values()) {
    // ...
}
Finally, if you want both the key and value, use entrySet():

for (Map.Entry entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}
One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer). However, changing item values is OK (see Map.Entry).
answered Jun 19, 2015 by rajesh
0 votes
public static class SmartHashMap {
    public HashMap keyValue;
    public HashMap valueKey;

    public SmartHashMap(){
        this.keyValue = new HashMap();
        this.valueKey = new HashMap();
    }

    public void add(T1 key, T2 value){
        this.keyValue.put(key, value);
        this.valueKey.put(value, key);
    }

    public T2 getValue(T1 key){
        return this.keyValue.get(key);
    }

    public T1 getKey(T2 value){
        return this.valueKey.get(value);
    }

}
answered Jun 19, 2015 by rajesh

...