iterator map java code example

Example 1: java map iteration

// 1. for-each with Entry
Map map = new HashMap();
for (Map.Entry entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}


// 2. for-each with key or value each (faster)
Map map = new HashMap();
//iterating over keys only
for (Integer key : map.keySet()) {
    System.out.println("Key = " + key);
}
 
//iterating over values only
for (Integer value : map.values()) {
    System.out.println("Value = " + value);
}


// 3. Using Iterator
Map map = new HashMap();
// With Generic
Iterator> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

// No Generic
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = (Map.Entry) entries.next();
    Integer key = (Integer)entry.getKey();
    Integer value = (Integer)entry.getValue();
    System.out.println("Key = " + key + ", Value = " + value);
}

Example 2: java iterate through map

for (Map.Entry entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}

Example 3: iterate hashmap java

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
    }
}

Example 4: iterate through map

//traditional way (long)
for(map::iterator it=m.begin(); it!=m.end(); ++it)
	if(it->second)cout<first<<" ";
//easy way(short) just works with c++11 or later versions
for(auto &x:m)
	if(x.second)cout<

Tags:

Misc Example