java how to iterate through a map 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 for map

Map map = new HashMap<>();

for(Entry entry:map.entrySet()) {
  System.out.println("key: "+entry.getKey()+" value: "+entry.getValue());
}

Example 3: java iterate through map

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

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: