Open In App

How to Sort ArrayList using Comparator?

Last Updated : 15 Dec, 2020
Comments
Improve
Suggest changes
7 Likes
Like
Report

Comparator is an interface that is used for rearranging the Arraylist in a sorted manner. Comparator is used to sort an ArrayList of User-defined objects. In java, Comparator is provided in java.util package. Using Comparator we can sort ArrayList on the basis of multiple variables. We can simply implement Comparator without affecting the original User-defined class. To sort an ArrayList using Comparator we need to override the compare() method provided by comparator interface. After rewriting the compare() method we need to call collections.sort() method like below.

Syntax:

Collections.sort(list, comparator)

Parameters:

  • list: List which should be sorted based on the comparator.
  • comparator: Comparator class instance

Returns: It sorts the list and does not return anything.

Example


Output
before sorting
520 Pen 218
213 Pencil 223
101 Books 423
59 Toy 512
10 Bottle 723

After sorting(sorted by Stock)
10 Bottle 723
59 Toy 512
101 Books 423
213 Pencil 223
520 Pen 218

In the above example, we sort the Shop class by the number of stock available. We can also sort it on the basis of name and ProductNo. Let's sort the above ArrayList based on the name.

Example 2


Output
before sorting
Pen 520 218
Pencil 213 223
Books 101 423
Toy 59 512
Bottle 10 723

After sorting(sorted by Name)
Books 101 423
Bottle 10 723
Pen 520 218
Pencil 213 223
Toy 59 512

Similar Reads