Iterate through the entrySet like so:
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
If you're only interested in the keys, you can iterate through the keySet() of the map:
Map<String, Object> 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<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
Source;- stackoverflow
Example Code:-
MapIteration.java
package collection.iteration;
import java.util.*;
import java.util.Map.Entry;
public class MapIteration {
public static void main(String[] args) {
Map <String,Employee> map= new HashMap<String,Employee>();
Employee emp1= new Employee(25, "Hitesh");
Employee emp2= new Employee(26, "Rajan");
Employee emp3= new Employee(27, "Dinesh");
Employee emp4= new Employee(24, "Neha");
map.put("e1",emp1);
map.put("e2",emp2);
map.put("e3",emp3);
map.put("e4",emp4);
System.out.println(map.keySet()); // Displaying all keys
System.out.println(map.values()); // Displaying all values
for(Map.Entry<String, Employee> entry : map.entrySet()){
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}
And
Employee.java
package collection.iteration;
public class Employee implements Comparable<Employee> {
int age;
String name;
Employee(int age, String name){
this.age=age;
this.name=name;
}
Employee(){
}
public String toString(){
return("The age is "+age+" and the name is "+name);
}
public int compareTo(Employee e){
return name.compareTo(e.name);
}
}
Output:
[e3, e4, e1, e2]
[The age is 27 and the name is Dinesh, The age is 24 and the name is Neha, The age is 25 and the name is Hitesh, The age is 26 and the name is Rajan]
e3
The age is 27 and the name is Dinesh
e4
The age is 24 and the name is Neha
e1
The age is 25 and the name is Hitesh
e2
The age is 26 and the name is Rajan
Regards
Rajan Bansal