Sorting data using Stream API in Java

Sorting refers to the mechanism of arranging/re-arranging something in a specific order. When it comes to java, we talk about placing the elements of an array or a list (Collection) in either Ascending or Descending order. There are multiple ways of achieving the desired order of elements in a collection, but here we will see how to make efficient use of Stream API which was introduced since JDK 8.

As we already know, streams work with Lambda expressions and Functional Interfaces and provide some out of the box features which make developers’ life easier. To sort a collection, streams have the inbuilt method sorted()  which has the following 2 method signatures:

1. Stream<T> sorted();
If we have to use this method, the elements of collection must be comparable i.e. the element 
object must implement Comparable interface. It will sort the collection according to the 
natural order of underlying object.
2. Stream<T> sorted(Comparator<? super T> comparator);
This one takes in the Comparator interface as an argument. Here, the developer has to specify 
the order of sorting.

Let’s explore both of these approaches. I assume that you have created a simple java project with Main.java class. First we have to create a POJO class named Employee.java with following signature:

public class Employee {
    private int id;
    private String name;
    private int age;
    private LocalDateTime lastUpdated;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public LocalDateTime getLastUpdated() {
        return lastUpdated;
    }

    public void setLastUpdated(LocalDateTime lastUpdated) {
        this.lastUpdated = lastUpdated;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", lastUpdated=" + lastUpdated.format(DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss")) +
                '}';
    }
}

Next, in Main.java we experiment with sorting techniques on-by-one. Create a static method in this class which fills up the data in the List.

private static List<Employee> populateEmployeeList() {
    Set<Employee> employeeList = new HashSet<>(5);
    for (int i = 1; i <= 5; i++) {
        Employee e = new Employee();
        e.setId(i);
        e.setName("Employee " + i);
        e.setAge(25 + i);
        e.setLastUpdated(LocalDateTime.now().plusDays(Long.parseLong(i + "")));

        employeeList.add(e);
    }
    return List.copyOf(employeeList);
}

Now let us create a utility method to print the elements of a collection, you can omit this step as I have included it in order to avoid repetition of code.

private static void printEmployees(List<Employee> employees) {
    employees.forEach(System.out::println);
    System.out.println();
}

With this we come to the main step where we sort data in different ways.

1. Sort by employee name using lambda expression in Ascending order:

employees = employees.stream().sorted((e1, e2) -> e1.getName().compareTo(e2.getName())).toList();
System.out.println("Variant 1 - Name Wise Sorted Employees: ");
printEmployees(employees);

2. Sort by employee name using method reference in Ascending order:

employees = employees.stream().sorted(Comparator.comparing(Employee::getName)).toList();
System.out.println("Variant 2 - Name Wise Sorted Employees: ");
printEmployees(employees);

3. Sort by employee name using lambda expression in Descending order:

employees = employees.stream().sorted((e1, e2) -> e2.getName().compareTo(e1.getName())).toList();
System.out.println("Variant 1 - Name Wise Sorted Employees in reverse order: ");
printEmployees(employees);

4. Sort by employee name using method reference in Descending order:

employees = employees.stream().sorted(Comparator.comparing(Employee::getName).reversed()).toList();
System.out.println("Variant 2 - Name Wise Sorted Employees in reverse order: ");
printEmployees(employees);

Conclusion

To conclude, we have seen that Streams are too useful when it comes to sorting because we have to deal with lesser and cleaner code. These have an upper hand on the performance side too.

I have given the link to my GitHub repo with the complete project setup, just checkout the repo and you are good to go. Thanks for reading the article. Please have a look at some of the other interesting posts here. Have a great day ahead!

1 thought on “Sorting data using Stream API in Java”

Leave a comment