Sorting of ArrayList in Java using Comparators

In this article we will see the sorting of arraylist in java using comparators. This is mainly used for sorting arraylist that contain user defined objects.

Collection.sort() takes 2 parameters.
1st parameter is the list that needs to be sorted.
2nd parameter is the object of the class that implements the Comparator.

For the comparator to perform its job we need to implement the compareTomethod.

Collection.sort() internal uses the compareTo method and decides the sorted list.

Lets create a object named Employee

Now to sort a list that contains Employee ,based on the salary we need to write a Comparator implementation as below

Please Note:

The return value of the compare method decides the equality of the objects.
If return value is a negative number – Object 1 is less than Object 2
If return value is a positive number – Object 1 is greater than Object 2
If return value is 0 – Object 1 is equal to Object 2

Now we will use the SalaryComparator class to sort the list

OutPut

*****Before Sorting*****
John::4000
Scott::8700
Stuart::5500
Bob::1000
*****After Sorting*****
Bob::1000
John::4000
Stuart::5500
Scott::8700

Sorting of ArrayList using multiple Comparators

Instead of creating a new class for Comparator, we can directly create a instance of the Comparator interface and use it in the sort method as shown in below example.

We can use this to create multiple sort alogrithm.

In the below example we are creating 2 sort alogo’s – on Salary and on Experience

Output

*****Before Sorting*****
John:: Salary – 4000 :: Exp -2
Scott:: Salary – 8700 :: Exp -5
Stuart:: Salary – 5500 :: Exp -10
Bob:: Salary – 1000 :: Exp -12
*****After Sorting Based on Salary*****
Bob:: Salary – 1000 :: Exp -12
John:: Salary – 4000 :: Exp -2
Stuart:: Salary – 5500 :: Exp -10
Scott:: Salary – 8700 :: Exp -5
*****After Sorting Based on Years of Experience****
John:: Salary – 4000 :: Exp -2
Scott:: Salary – 8700 :: Exp -5
Stuart:: Salary – 5500 :: Exp -10
Bob:: Salary – 1000 :: Exp -12

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn