Thursday 15 June 2023

How to sort a list of objects in java 8 with stream?

 In Java 8, you can use the Stream API to sort a list of Employee objects based on name and ID. Here's an example:

java
import java.util.ArrayList; 
import java.util.Comparator; 
import java.util.List; 
class Employee
private int id; 
private String name;
public Employee(int id, String name) {
this.id = id; 
this.name = name;
 }
public int getId()
return id; 
 } 
public String getName()
return name; 
 } 
@Override public String toString() {
return "Employee{" + "id=" + id + ", name='" + name + '\'' + '}'
 } 
public class EmployeeSortingExample {
public static void main(String[] args)
 List<Employee> employees = new ArrayList<>(); 
 employees.add(new Employee(3, "John")); 
 employees.add(new Employee(1, "Alice")); 
 employees.add(new Employee(2, "Bob")); 
// Sort by name List<Employee> sortedByName = employees.stream() .sorted(Comparator.comparing(Employee::getName)) .toList();
 System.out.println("Sorted by name:");
 sortedByName.forEach(System.out::println);
// Sort by ID List<Employee> sortedById = employees.stream() .sorted(Comparator.comparingInt(Employee::getId)) .toList(); System.out.println("Sorted by ID:"); sortedById.forEach(System.out::println); 
 } 
}

In this example, we use the stream() method to convert the List of employees into a stream. Then we use the sorted method along with a comparator created using Comparator.comparing() to specify the property to sort on (Employee::getName for name and Employee::getId for ID).

The sorted method returns a new sorted stream, and we use the toList method to collect the sorted elements into a new List.

After sorting the streams and collecting the sorted elements into new lists, we use the forEach method to iterate over the sorted lists and print the employees' details. The System.out::println method reference is used as a lambda expression to print each employee.

No comments:

Post a Comment