How to Implement a Custom Comparator for a LinkedHashSet in Java?
Last Updated :
07 Feb, 2024
In Java, we cannot directly implement a custom comparator for a LinkedHashSet. But sometimes we need a requirement of custom comparator for example custom sorting. So, we can use some alternative approaches to fulfill the requirements.
In this article, we will be using a class for creating the custom comparator and this class will implement the Comparable interface for a LinkedHashSet in Java.
Approach:
- In the first step, we have created a class which is the type of Employee, and implemented a Comparable interface.
- It accepts a value of Employee type in a constructor and accepts UserIDs.
- Then Override compareTo method.
- We also Override a toString method for printing the output.
- Now we create the LinkedHashSet of type Employee and add Employee ID.
- Then we add these LinkedHashSet values to an ArrayList.
- So, we can use Collection.Sort which sorts the elements by User IDs.
- Then we print the output.
Program to Implement a Custom Comparator for a LinkedHashSet in Java
Suppose we have a LinkedHashSet of Employee IDs and want to perform a custom sorting, for this follow the below implementation.
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
class Employee implements Comparable<Employee> {
private int employeeId;
public Employee( int id) {
this .employeeId = id;
}
public int getId() {
return this .employeeId;
}
public String toString() {
return "Employee -> " + getId();
}
public int compareTo(Employee otherEmployee) {
return this .getId() - otherEmployee.getId();
}
}
public class GFG {
public static void main(String[] args) {
LinkedHashSet<Employee> setOfEmployees = new LinkedHashSet<>();
setOfEmployees.add( new Employee( 3 ));
setOfEmployees.add( new Employee( 1 ));
setOfEmployees.add( new Employee( 2 ));
List<Employee> listUsers = new ArrayList<>(setOfEmployees);
Collections.sort(listUsers);
System.out.println(listUsers);
}
}
|
Output
[Employee -> 1, Employee -> 2, Employee -> 3]
Explanation of the Program:
- In the above program, we have defined a class
Employee
that implements the Comparable
interface. The compareTo
method is implemented to compare Employee
objects based on their employee IDs.
- We create a
LinkedHashSet
named setOfEmployees
to store Employee
objects. Note that LinkedHashSet
maintains insertion order.
- We convert the
LinkedHashSet
to an ArrayList
named listUsers
to perform sorting. This is done to demonstrate sorting using the custom comparator.
- We sort the
listUsers
using Collections.sort
method, which uses the custom comparator defined in the Employee
class.
- Finally, we print the sorted list.
Share your thoughts in the comments
Please Login to comment...