Let us add a few values to a HashMap and see how do we fetch them.
public class TestCollection{ public static void main(String[] arg){ MapmyHashMap = new HashMap (); myHashMap.put(1,"John"); myHashMap.put(2,"Paul"); myHashMap.put(3,"Tom"); for(Map.Entry entry: myHashMap.entrySet()) { System.out.println("The key is : "+entry.getKey()+" and the value is : "+entry.getValue()); } } }
In the above code, after we have added three Entries(i.e. Key and Value Pair) to the HashMap. We have used the for each loop to iterate the Entries of the Map.
for(Map.Entry entry: myHashMap.entrySet()) { System.out.println("The key is : "+entry.getKey()+" and the value is : "+entry.getValue()); }
A Key - Value pair in a map is called as an Entry. So, in the Map interface there is an Entry interface.
And Map.Entry type object actually holds a key - value pair or an Entry.
So, to fill this Map.Entry entry, we need a Set of HashMaps in the form of Key - Value pairs.
Now, myHashMap.entrySet() solves this purpose. entrySet() method returns a Set of key and values from the HashMap.
for(Map.Entry entry: myHashMap.entrySet())
So, when we get the key - value pair in the entry object of Map.Entry. We can get the key using entry.getKey() and value using entry.getValue().
System.out.println("The key is : "+entry.getKey()+" and the value is : "+entry.getValue());
If we look at the output, the order is not maintained. Because the insertion is based on HashCode of the key.