1. Introduction
Sorting a List in Java can be accomplished using various methods, but sometimes we need to sort a list of custom objects which may not have a natural ordering. In this tutorial, we will look at how we can sort a List of custom objects using a comparator.
2. Program Steps
1. Import necessary libraries.
2. Define a custom class Employee with fields id and name.
3. Initialize a List of Employee objects.
4. Define a custom Comparator for comparing Employee objects based on their name.
5. Sort the List using the sort() method and the custom Comparator.
6. Print the sorted List.
3. Code Program
// Step 1: Import necessary libraries
import java.util.List;
import java.util.Comparator;
import java.util.Arrays;
// 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 CustomSortListExample {
public static void main(String[] args) {
// Step 3: Initialize a List of Employee objects
List<Employee> employeeList = Arrays.asList(
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: Sort the List using the sort() method and the custom Comparator
employeeList.sort(nameComparator);
// Step 6: Print the sorted List
System.out.println("Sorted Employee List: " + employeeList);
}
}
Output:
Sorted Employee List: [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 lists, comparators, and arrays.
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 List named employeeList containing several Employee objects.
Step 4: Define a custom Comparator named nameComparator for comparing Employee objects based on their name.
Step 5: Use the sort() method on the employeeList, passing the nameComparator as an argument, to sort the Employee objects based on their names.
Step 6: Print the sorted List which shows the Employee objects sorted in ascending order by their names.