Java – What is LinkedHashMap and what is it used for?

What is LinkedHashMap and what is it used for?… here is a solution to the problem.

What is LinkedHashMap and what is it used for?

When I looked at the sample code containing the ListView, I thought of LinkedHashMap.
What is LinkedHashMap, where and how can we use it? I went through several articles and didn’t fully understand. Whether it is required when creating a ListView. What is the connection between ListViews and LinkedHashMaps? Thank you.

Solution

For simplicity, let’s understand the difference between HashMap and LinkedHashMap.

HashMap: It provides output in random order, which means we insert values in the wrong order.

Whereas

LinkedHashMap: It gives output in order.

Let’s look at a small example: using HashMap

    // suppose we have written a program
    .
    .
     now use HashMap
    HashMap map = new HashMap();   create object
    map.put(1,"Rohit");           insert values
    map.put(2,"Rahul");
    map.put(3,"Ajay");

System.out.println("MAP=" +map); print the output using concatenation

So the output may be in any order like we can say the output may be as:
    Map={3=Ajay,2=Rahul,1=Rohit}

But that’s not the case in LinkedHashMap
Just replace “HashMap” with “LinkedHashMap” in the code above
Look
It will display the outputs sequentially, e.g. 1=Rohit will display first, and then the other outputs in order.

Related Problems and Solutions