Java 8 – Comparator improvements (Easy null handling, Easy with streams, comparator chaining, reversal)

Java 8 has added lots of good to use methods to make it easy to use with streams, easy to handle nulls, chain comparators, reverse order etc. We will take simple example to understand new improvements to Comparator in Java 8.

Example:

  • Create comparator for Person class which has two attributes & getter/setters – name & age
  • Comparator should handle null values and treat null as last in sorting.
  • Comparator should first compare based on name in ascending order.
  • If names are same, then it should compare based on age.

Before Java 8:

Before Java 8, comparator will look something like below which satisfied all conditions above.

Test:

Output:

 

With Java 8 improvements:

Well with Java 8, we don’t even need to prepare separate comparator implementation class to achieve above requierments.

Output:

 

Easy Reversal: Its also very easy to reverse the order just using Comparator.reversed()

Output:

 

Easy to use with streams:  This also makes it very easy to use with Java streams as shown in below example.

Output:

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *