1. Introduction
In Java, a Set is a collection that does not allow duplicate elements. However, a Set does not guarantee any specific order of the elements. Sometimes, we need to sort the elements in a Set in a custom order. This tutorial will show you how to perform custom sorting on a Set using a TreeSet and a custom Comparator.
2. Program Steps
1. Import necessary libraries.
2. Define a custom class Employee with fields id and name.
3. Initialize a Set of Employee objects.
4. Define a custom Comparator for comparing Employee objects based on their name.
5. Initialize a TreeSet with the custom Comparator and add all elements from the original Set.
6. Print the sorted Set.
3. Code Program
// Step 1: Import necessary libraries
import java.util.Set;
import java.util.HashSet;
import java.util.Comparator;
import java.util.TreeSet;
// Step 2: Define a custom class Employee with fields id and name
class Employee {
int id;
String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Employee{id=" + id + ", name='" + name + '\'' + '}';
}
}
public class CustomSortSetExample {
public static void main(String[] args) {
// Step 3: Initialize a Set of Employee objects
Set<Employee> employeeSet = new HashSet<>(Set.of(
new Employee(1, "John"),
new Employee(2, "Alice"),
new Employee(3, "Bob")
));
// Step 4: Define a custom Comparator for comparing Employee objects based on their name
Comparator<Employee> nameComparator = Comparator.comparing(Employee::getName);
// Step 5: Initialize a TreeSet with the custom Comparator and add all elements from the original Set
Set<Employee> sortedSet = new TreeSet<>(nameComparator);
sortedSet.addAll(employeeSet);
// Step 6: Print the sorted Set
System.out.println("Sorted Employee Set: " + sortedSet);
}
}
Output:
Sorted Employee Set: [Employee{id=2, name='Alice'}, Employee{id=3, name='Bob'}, Employee{id=1, name='John'}]
4. Step By Step Explanation
Step 1: Import the necessary libraries for working with sets, comparators, and treesets.
Step 2: Define a custom Employee class with fields id and name. Override the toString() method for better readability of the output.
Step 3: Initialize a Set named employeeSet containing several Employee objects.
Step 4: Define a custom Comparator named nameComparator for comparing Employee objects based on their name.
Step 5: Initialize a TreeSet named sortedSet with the nameComparator and add all elements from the original employeeSet to it. The TreeSet will automatically sort the elements based on their names.
Step 6: Print the sorted Set, which shows the Employee objects sorted in ascending order by their names.