How to sort keys in TreeMap by using comparator with user defined objects in java

The TreeMap in Java is employed to implement the Map interface and NavigableMap alongside the AbstractMap Class. The map is sorted consistent with the natural ordering of its keys, or by a Comparator provided at map creation time, counting on which constructor is employed. To sort keys in TreeMap by employing a comparator with user-defined objects in Java we've to make a category that implements the Comparator interface to override the compare method.

// AccordingMarks class that implements the 
// comparator interface to override compare method

class AccordingMarks implements Comparator {
    public int compare(Student s1, Student s2) {
        return s1.getMarks().compareTo(s2.getMarks());
    }
}

In the code below, we pass the custom object as the key in the TreeMap, which is the Student user-defined class. In this case, we need to pass the comparator according to the mark in the constructor, and at the same time create a TreeMap object that sorts the TreeMap according to the student's score.

Example 1: Sort keys in ascending order of the marks

// Java program to demonstrate how to sort TreeMap of custom
// class objects
import java.util.*;

// Custom class
class Student {

	private String name;
	private int marks;

	public Student(String name, Integer marks)
	{
		this.name = name;
		this.marks = marks;
	}

	public String getName() { return this.name; }

	public Integer getMarks() { return this.marks; }
	// override toString method
	public String toString()
	{
		return this.name + ": " + marks;
	}
}

// Comparator that sort elements according to marks in
// Accending order
class AccordingMarks implements Comparator {
	public int compare(Student s1, Student s2)
	{
		return s1.getMarks().compareTo(s2.getMarks());
	}
}

// Driver Code
public class GFG {
	public static void main(String[] args)
	{

		// New TreeMap of custom class Student
		TreeMap<Student, Integer> map
			= new TreeMap<>(new AccordingMarks());

		// Add elements to TreeMap
		map.put(new Student("Akshay", 400), 1);
		map.put(new Student("Bina", 500), 2);
		map.put(new Student("Chintu", 300), 3);

		System.out.println(
			"TreeMap keys sorting in Accending order of the marks:");

		// Print map using Entry
		for (Map.Entry<Student, Integer> entry :
			map.entrySet()) {
			System.out.println("Key : (" + entry.getKey()
							+ "), Value : "
							+ entry.getValue());
		}
	}
}

Output

TreeMap keys sorting in Accending order of the marks:
Key : (Chintu: 300), Value : 3
Key : (Akshay: 400), Value : 1
Key : (Bina: 500), Value : 2

Example 2: Sort keys into descending order of the mark

// Java program to demonstrate how to sort TreeMap of custom
// class objects
import java.util.*;

// Custom class
class Student {

	private String name;
	private int marks;

	public Student(String name, Integer marks)
	{
		this.name = name;
		this.marks = marks;
	}

	public String getName() { return this.name; }

	public Integer getMarks() { return this.marks; }
	// override toString method
	public String toString()
	{
		return this.name + ": " + marks;
	}
}

// Comparator that sort elements according to marks in
// Decending order
class AccordingMarks implements Comparator {
	public int compare(Student s1, Student s2)
	{
		return s2.getMarks().compareTo(s1.getMarks());
	}
}

// Driver Code
public class GFG {
	public static void main(String[] args)
	{

		// New TreeMap of custom class Student
		TreeMap<Student, Integer> map
			= new TreeMap<>(new AccordingMarks());

		// Add elements to TreeMap
		map.put(new Student("Akshay", 400), 1);
		map.put(new Student("Bina", 500), 2);
		map.put(new Student("Chintu", 300), 3);

		System.out.println(
			"TreeMap Keys sorted in Decending order of the marks: ");

		// Print map using Entry
		for (Map.Entry<Student, Integer> entry :
			map.entrySet()) {
			System.out.println("Key : (" + entry.getKey()
							+ "), Value : "
							+ entry.getValue());
		}
	}
}

Output

TreeMap Keys sorted in Decending order of the marks: 
Key : (Bina: 500), Value : 2
Key : (Akshay: 400), Value : 1
Key : (Chintu: 300), Value : 3

 

Submit Your Programming Assignment Details