Comparator

Sort ArrayList using Comparator example

With this example we are going to demonstrate how to sort an ArrayList using a Comparator. We are using Collections API, that provides methods to get and use a Comparator. In short, to sort an ArrayList using a Comparator you should:

  • Create a new ArrayList.
  • Populate the arrayList with elements, using add(E e) API method of ArrayList.
  • Invoke reverseOrder() API method of Collections to get a Comparator that imposes the reverse of the natural ordering on the list’s elements.
  • Invoke sort(List list, Comparator c) API method of Collections in order to sort the arrayList elements using the comparator. The arrayList’s elements will be sorted according to the comparator.
  • We can get the arrayList’s elements before and after sorting to check how they are sorted. Before sorting the arrayList elements are sorted by insertion order, and after sorting the elements are in reverse than the natural ordering.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
 
public class SortArrayListComparator {
 
  public static void main(String[] args) {
 
    // Create an ArrayList and populate it with elements
    ArrayList arrayList = new ArrayList();
    arrayList.add("element_1");
    arrayList.add("element_3");
    arrayList.add("element_5");
    arrayList.add("element_2");
    arrayList.add("element_4");
 
    // ArrayList implementation maintains the insertion order for its elements
    System.out.println("Elements in ArrayList prior sorting :");
    for(int i=0; i < arrayList.size(); i++)

System.out.println(arrayList.get(i));

    /*

To get a comparator that imposes reverse order on a Collection's elements 

we can use static Comparator reverseOrder() operation of Collections class
    */
    Comparator comparator = Collections.reverseOrder();
 
    // Collection.sort(List list, Comparator c) static operation sorts ArrayList elements using a Comparator
    Collections.sort(arrayList,comparator);

    System.out.println("Elements in ArrayList after sorting :");
    for(int i=0; i < arrayList.size(); i++)

System.out.println(arrayList.get(i));
 
  }
}

Output:

Elements in ArrayList prior sorting :
element_1
element_3
element_5
element_2
element_4
Elements in ArrayList after sorting :
element_5
element_4
element_3
element_2
element_1

 
This was an example of how to sort an ArrayList using a Comparator in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button