Open In App

Sort LinkedHashMap by Keys using Comparable Interface in Java

Last Updated : 04 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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


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


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}

Next Article
Practice Tags :

Similar Reads