Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Iterate a Map


How to Iterate a HashMap/Map?


Let us add a few values to a HashMap and see how do we fetch them.


Example :



public class TestCollection{
	public static void main(String[] arg){
	
		Map myHashMap = 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());
            
        }		
	}
}


Output :



  The key is : 1 and the value is : John
  The key is : 3 and the value is : Tom
  The key is : 2 and the value is : Paul

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.