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




Java - LinkedHashMap

LinkedHashMap is a child of HashMap, that maintains the order. i.e. The order in which you have inserted the element, in the same order the elements will be retrieved.

Lets look at the below example :

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){

    Map <Integer,String> myLinkedHashMap = new LinkedHashMap <Integer,String>();

    myLinkedHashMap.put(1,"John");
    myLinkedHashMap.put(2,"Paul");
    myLinkedHashMap.put(3,"Tom");

    for(Map.Entry entry: myLinkedHashMap.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 : 2 and the value is : Paul
   The key is : 3 and the value is : Tom


Firstly we have defined the LinkedHashMap.


Map <Integer,String> myLinkedHashMap = new LinkedHashMap <Integer,String>();

Then we have added three Entries to the Map and Iterated using for each loop.

When we see the output, it is in the same order in which it was inserted.