Software Development

Java – Sort Objects in Collections

[wp_ad_camp_1]

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.

[wp_ad_camp_2]

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.

[wp_ad_camp_3]

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like