Java Program to Sort LinkedHashMap By Values
Last Updated :
08 Sep, 2022
The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion, but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order.
Hence LinkedHashMap Is the child class of HashMap. Now, in LinkedHashMap insertion order has to be maintained, so convert the LinkedHashMap into a list and after that print the list in which values are in sorted order.
Illustration:
Input : LinkedHashMap = {{“for”, 2}, {“Geek”, 3}, {“Geeks”, 1}}
Output:
Key -> Geeks : value -> 1
Key -> for : value -> 2
Key -> Geek : value ->3
Procedure:
- Create an object of LinkedHashMap Class where the object is declared of type Integer and String.
- Add elements to the above object created of the map using the put() method. Elements here are key-value pairs.
- Retrieve above all entries from the map and convert them to a list using entrySet() method.
- Sort the value of the list using the custom comparator.
- Now use the Collections class sort method inside which we are using a custom comparator to compare the value of a map.
- Print the above list object using for each loop.
Implementation:
Example
Java
import java.util.*;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
class GFG {
public static void main(String[] args)
{
LinkedHashMap<String, Integer> map
= new LinkedHashMap<>();
map.put( "for" , 2 );
map.put( "Geek" , 3 );
map.put( "Geeks" , 1 );
List<Map.Entry<String, Integer> > list
= new ArrayList<Map.Entry<String, Integer> >(
map.entrySet());
Collections.sort(
list,
new Comparator<Map.Entry<String, Integer> >() {
public int compare(
Map.Entry<String, Integer> entry1,
Map.Entry<String, Integer> entry2)
{
return entry1.getValue()
- entry2.getValue();
}
});
for (Map.Entry<String, Integer> l : list) {
System.out.println( "Key ->"
+ " " + l.getKey()
+ ": Value ->"
+ l.getValue());
}
}
}
|
Output
Key -> Geeks: Value ->1
Key -> for: Value ->2
Key -> Geek: Value ->3
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...