map iteration in java code example
Example 1: java map iteration
// 1. for-each with Entry
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
// 2. for-each with key or value each (faster)
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//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<Integer, Integer> map = new HashMap<Integer, Integer>();
// With Generic
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Integer> 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<String, String> map = new HashMap<>();
for(Entry<String, String> entry:map.entrySet()) {
System.out.println("key: "+entry.getKey()+" value: "+entry.getValue());
}
Example 3: foreach map java
Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
Example 4: java iterate through map
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
Example 5: java foreach map
map.forEach((k, v) -> System.out.printf( " %s : %d \n" , k,v) );
Example 6: iterate through map
//traditional way (long)
for(map<string,int>::iterator it=m.begin(); it!=m.end(); ++it)
if(it->second)cout<<it->first<<" ";
//easy way(short) just works with c++11 or later versions
for(auto &x:m)
if(x.second)cout<<x.first<<" ";
//condition is just an example of use