Hello guys, as a Java developer we often need to sort List like ArrayList, LinkedList, or CopyOnWriteArrayList and while I have share many articles on sorting a list in Java in both increasing order and deceasing order as well as sorting ArrayList in a custom order using Comparator, things have changed a lot in Java world, especially after Java 8 when Lambda expression and method reference was first introduced. Now there are more declarative and expressive way to sort a List of object in different order based upon different conditions. Enhancements made on Comparator API has also made comparing and sorting object in Java much easier and I have shown the power of new Comparator API in my earlier article about advanced Java Comparator example. I was particularly impressed with comparing() and thenComparing() as they literally make comparison on multiple condition easier.
While all the articles which I have shard about sorting List in Java are still valid and you can use them to sort both ArrayList and LinkedList, knowing how to sort a List using Lambda expression is imperative for modern and experienced developers.
Most of the senior folks in banks and different organization where Java is used pushes use of Java 8 language syntax like Lambda and Stream during code review and they will often ask you to rewrite code using functional programming to make it more declarative. Knowing how to do that, will not only make a better programmer but also improve your chances in Java developer interviews.
In this Java List tutorial, I will show you different ways to sort a List like ArrayList using Lambda Expression and method reference and then you will judge yourself whether old way is better or this new way is better and more expressive.
8 ways to Sort List in Java 8 using Lambda Expression
Here is the Java program to demonstrate all those ways of sorting List using lambdas in Java 8. You need to install Java 8 to run this program, alternatively you can also copy paste this program and run in any web based IDE.And, here is the 8 ways to sort a List like ArrayList, LinkedList, Vector, or CopyOnWriteArrayList in Java using Lambda Expression:
1. Using Anonymous inner class as shown in first example
2. Sorting List with lambda expressions in Java 8
4. Sorting List using Lambda + Method reference
5. Sorting using new Comparator.comparing() method
6. Sorting List in reverse order using Lambda
7. Sorting List on multiple parameters
8. Sorting List using combination of comparing() and thenComparing methods
And, here is complete Java program for you to play with. You can also copy individual piece of code and run in on jshell, a command line utility which comes with JDK (after JDK 9) which allows you to run Java code like commands.
package test; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Java program to demonstrate how to sort List in Java 8 * using lambda expression, * method reference, and static utility method added on Comparator interface*
* comparing() and thenComparing()
* @author Javin Paul * */ public class Java8ListSorter{ public static void main(String[] args) { // Initializing List for our example ListempList = Arrays.asList(new Employee(101, "Jack", 22), new Employee(201, "Abhay", 23), new Employee(301,"Tom", 24), new Employee(401, "Jack", 52)); System.out.println("Printing List of employees using Java 8 forEach and method reference"); empList.forEach(System.out::println); //Example 1 - Sorting without lambda expressions, like prior Java 8 Collections.sort(empList, new Comparator (){ @Override public int compare(Employee e1, Employee e2) { return e1.getId() - e2.getId(); } }); //Printing sorted list of objects using forEach method System.out.println("Sorted List of Objects by id : "); System.out.println(empList.get(0)); //Example 2 - Sorting List with lambda expressions in Java 8 // This time sorting employees based on their name Collections.sort(empList, (Employee e1, Employee e2) -> e1.getName().compareTo(e2.getName())); System.out.println("Sorted List of Employees by name : "); System.out.println(empList.get(0)); //Example 3 - improved use of lambdas, using type inference // Sorting employee objects by their age Collections.sort(empList,(e1, e2) -> e1.getAge() - e2.getAge()); System.out.println("Employee object sorted by their age"); System.out.println(empList.get(0)); // Example 4 - Sorting List in Java 8 using lambdas and static // method reference // Sorting List of employee by their name, age Collections.sort(empList, Employee::compareByNameAndAge); System.out.println("Sorting employees by name and age"); empList.forEach(System.out::println); //Example 5 - Sorting List using Comaprator's comparing() method Collections.sort(empList, Comparator.comparing(Employee::getName)); System.out.println("Employee sorted by name using comparing() method of Comparator"); System.out.println(empList.get(0)); //Example 6 - Sorting List in reverse Order - Java 8 lambdas example Comparator java8Cmp = (e1, e2) -> e1.getId() - e2.getId(); Collections.sort(empList, java8Cmp.reversed()); System.out.println("Sorting employees in reverse order of id"); empList.forEach(System.out::println); //Example 7 - Sorting list of objects based on multiple conditions Collections.sort(empList, (e1, e2) -> { if (e1.getName().equals(e2.getName())) { return e1.getAge() - e2.getAge(); }else{ return e1.getName() .compareTo(e2.getName()); } }); //Example 8 - Java 8 example of chaining Comparator for sorting //on multiple case // first comparing Age, using thenComparing() method of Comparator Comparator byName = (e1, e2) -> e1.getName().compareTo(e2.getName()); Comparator byAge = (e1, e2) -> e1.getAge() - e2.getAge(); Collections.sort(empList, byAge.thenComparing(byName).reversed()); System.out.println("Sorting empoyess on multple conditions, by age then name"); empList.forEach(System.out::println); //Example 9 - How to sort List in Java 8 using static method reference //Example 10 - Sorting list using parallel Stream Java 8 } }
and here is our value class Employee to be used in this example
/* * Our simple Java POJO class for this example */ class Employee{ private int id; private String name; private int age; public Employee(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } 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; } @Override public int hashCode() { int hash = 7; hash = 89 * hash + this.id; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Employee other = (Employee) obj; return this.id == other.id; } @Override public String toString() { return String.format("Id: %d, Name: %s, Age: %d", id, name, age); } public static int compareByNameAndAge(Employee emp1, Employee emp2){ if(emp1.getName().equals(emp2.getName())){ return emp1.getAge() - emp2.getAge(); } return emp1.getName().compareTo(emp2.getName()); } } Output: run: Printing List of employees using Java 8 forEach and method reference Id: 101, Name: Jack, Age: 22 Id: 201, Name: Abhay, Age: 23 Id: 301, Name: Tom, Age: 24 Id: 401, Name: Jack, Age: 52 Sorted List of Objects by id : Id: 101, Name: Jack, Age: 22 Sorted List of Employees by name : Id: 201, Name: Abhay, Age: 23 Employee object sorted by their age Id: 101, Name: Jack, Age: 22 Sorting employees by name and age Id: 201, Name: Abhay, Age: 23 Id: 101, Name: Jack, Age: 22 Id: 401, Name: Jack, Age: 52 Id: 301, Name: Tom, Age: 24 Employee sorted by name using comparing() method of Comparator Id: 201, Name: Abhay, Age: 23 Sorting employees in reverse order of id Id: 401, Name: Jack, Age: 52 Id: 301, Name: Tom, Age: 24 Id: 201, Name: Abhay, Age: 23 Id: 101, Name: Jack, Age: 22 Sorting empoyess on multple conditions, by age then name Id: 401, Name: Jack, Age: 52 Id: 301, Name: Tom, Age: 24 Id: 201, Name: Abhay, Age: 23 Id: 101, Name: Jack, Age: 22 BUILD SUCCESSFUL (total time: 1 second)
If you have noticed, we are also using different ways o print List, prior to Java 8, we used to use a for-each loop to iterate over List and print each content, now we are using the forEach() method. This is added into the Iterable interface, also known as the default method or defender method, They are very critical for the application of lambdas.
That's all about How to sort a List using lambda expressions in Java 8. You have just seen the power of lambda expression in terms of creating concise but expressive code, and adding flexibility to JDK core classes like List, Comparator, etc.
Going forward, you should leverage lambda expression as much as possible to reduce boilerplate code and create beautiful pieces. 3rd example should be your general-purpose solution, use lambda expression with type inference, as a compiler is smart enough to resolve type.
Other Core Java Articles you may like:
- How to format/parse the date with LocalDateTime in Java 8? (tutorial)
- 5 Free Courses to learn Java 8 and 9 (courses)
- 20 Examples of Date and Time in Java 8 (tutorial)
- How to use filter() method in Java 8 (tutorial)
- How to sort the may by values in Java 8? (example)
- How to convert List to Map in Java 8 (solution)
- How to use Stream class in Java 8 (tutorial)
- 5 Books to Learn Java 8 from Scratch (books)
- Difference between abstract class and interface in Java 8? (answer)
- What is the default method in Java 8? (example)
- How to join String in Java 8 (example)
- How to sort the map by keys in Java 8? (example)
- 7 Best Collections and Stream Courses for Java developers (courses)
P. S. - If you are an experienced Java developer and want to master Java and become a Java Guru then you can also check out
this list of Top 10 Advanced Core Java Courses on Medium. It contains different Java courses to become an expert Java programmer.
No comments :
Post a Comment