Sort arraylist and collection in java (Comparable and Comparator)

This tutorial shows the use java.lang.Comparable and java.util.Comparator to sort arraylist and collection in java. The arraylist or collection may contain primitive data, string or user defined object. Here is is a good subject for any java programmer. Because if you know and understand how to sort arraylist and collection in Java(Comparable and Comparator) you will optimize your code

1. Sort an Array

Here is output

2. Sort an ArrayList

Here is output

3. Sort Array of objects using Comparable
You should use Person class for sorting java object. The Person class implements the Comparable interface, and override the compareTo() method to compare its age property.

You should use Arrays.sort() again to sort it.

Here is output

4. Sort Array of Object using Comparator
You could only sort a single property with the Comparable interface. To sort with multiple properties, you should use Comparator. Here you adapt the method PersonNameComparator implemented Comparator into the class Person.

Sort Person array with its “name” property in ascending order

Here is output

If you store person objects in a collection you could sort by using this code sample below

I hope that this tutorial sort arraylist and collection in java is useful for you.
Happy learning!

Leave a Comment


Please share it if you found this useful
Hide Buttons