Sort LinkedHashMap by Keys using Comparable Interface in Java
The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order.
To sort LinkedHashMap by keys using the comparable interface in Java first, we create a class that implements the comparable interface. In this class, we override the compareTo() method.
// Student class implements comparable interface
class Student implements Comparable<Student> {
String name;
Student(String name) {
this.name = name;
}
// Override toString method
public String toString() {
return this.name;
}
// Override compareTo method
public int compareTo(Student stu) {
return this.name.compareTo(stu.name);
}
}
And then we pass the LinkedHashMap to TreeMap constructor to sort.
TreeMap<Student, Integer> tree_map = new TreeMap<>(map);
Below is the full implementation of the approach:
Example 1
Java
import java.util.*;
class Student implements Comparable<Student> {
String name;
Student(String name) { this .name = name; }
public String toString() { return this .name; }
public int compareTo(Student stu)
{
return this .name.compareTo(stu.name);
}
}
class GFG {
public static void main(String[] args)
{
LinkedHashMap<Student, Integer> map
= new LinkedHashMap<>();
map.put( new Student( "Bina" ), 200 );
map.put( new Student( "Akshay" ), 400 );
map.put( new Student( "Chintu" ), 500 );
System.out.println(
"Before sort keys in ascending order : " + map);
TreeMap<Student, Integer> tree_map
= new TreeMap<>(map);
System.out.println(
"After sort keys in ascending order : "
+ tree_map);
}
}
|
Output
Before sort keys in ascending order : {Bina=200, Akshay=400, Chintu=500}
After sort keys in ascending order : {Akshay=400, Bina=200, Chintu=500}
Example 2
Java
import java.util.*;
class Student implements Comparable<Student> {
String name;
Student(String name) { this .name = name; }
public String toString() { return this .name; }
public int compareTo(Student stu)
{
return stu.name.compareTo( this .name);
}
}
class GFG {
public static void main(String[] args)
{
LinkedHashMap<Student, Integer> map
= new LinkedHashMap<>();
map.put( new Student( "Bina" ), 200 );
map.put( new Student( "Akshay" ), 400 );
map.put( new Student( "Chintu" ), 500 );
System.out.println(
"Before sort keys in descending order : " + map);
TreeMap<Student, Integer> tree_map
= new TreeMap<>(map);
System.out.println(
"After sort keys in descending order : "
+ tree_map);
}
}
|
Output
Before sort keys in descending order : {Bina=200, Akshay=400, Chintu=500}
After sort keys in descending order : {Chintu=500, Bina=200, Akshay=400}
Last Updated :
04 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...