Skip to main content

Sort data with Streams 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);
}
Then we 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 primary 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

In this post 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. Have a great day ahead!

Comments

Popular posts from this blog

Use PostgreSQL Full Text Search With HQL

Full Text Search (FTS) is a great mechanism that can be used to search the database against a search term. FTS can produce miraculous results when used efficiently. The PostgreSQL database has inbuilt library for FTS and provides various functions to make use of it. It also has a special data type called "tsvector" to store the keywords(tokens) that take part in the searching process. We are not going to discuss about how Postgres handles FTS, but we will discuss about how to use this with Hibernate HQL(Hibernate Query Language). For more info about full text searching with postgres, you can visit This link. To use FTS with Hibernate, we will have to first create a POJO (say PostgreSQLFullTextSearchFunction ) which implements SQLFunction interface. We are going to use the custom Dialect java class (say CustomPostgresDialect ) in the SessionFactory configuration. In this custom dialect class, you will have to register a new SQL function by passing the object of PostgreSQLF...

External Pagination & Sorting With Display Tag

We often come across the need to display data of any web application in a tabular form to the end user.There are several ways to do this using different kind of technologies e.g. Jquery's JQGrid etc. One such technology in JSP is to use the "displaytag" library. The display tag allows the programmer to provide the end user very basic but important features of: 1. Sorting the contents of the displayed list based on the sort order(Ascending/Descending) and sort property (First Name/Last Name etc.). 2. Navigating to other records if the list is quite large (Pagination). 3. Exporting the displayed data in any of the file formats like PDF, Excel etc. 4. Customizing the design (look & feel) of the displayed table via a properties file or inline properties. By default display table is configured to use the internal Pagination and Sorting. I am going to describe that how we can use the External pagination and/or sorting with display table in this post. Assuming that w...