Java – Sort Objects in Collections

Last Updated on

Before Java 8, sorting objects in collections is a bit awkward and verbose in terms of the amount of codes you need to put in. With Java 8, things got easier because of Lambda expressions.

Basically, we are using the same interface java.util.Comparator(i.e., no new interfaces provided) but modified to take advantage of the Lamba expressions introduced in Java 8.

Java 6 Comparator Interface

Check out the older version of java.util.Comparator at http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Comparator.java

As you can see, it only has those two abstract methods.

Using Comparator Interface with Collections

Here is an example that uses the java.util.Comparator interface in an old way with java.util.Collections class.

Java 8 Comparator Interface

Here is an example that uses the new java.util.Comparator interface using lambda expression.

Using Comparator Interface with Collections (Lambda version)

But the same old way can be modified a bit to use Lambda expression.

Karl San Gabriel

Karl San Gabriel

Professional Software Developer