Sorting ArrayList with Collections sort()

Collections algorithms makes a programmer's work easier and avoids lots of simple, but extra code. It is proved in each method of Collections class. The sorting algorithm places the elements in ascending order, known as natural order (a before b and 1 before 2). Internally, the data structure elements are converted into an array and mergesort (with n log(n) performance) is applied.

Two methods exist, with Collections class, for sorting elements. Following are the signatures.

  • static void sort(List list1): Sorts the list list1 into ascending order according to the natural sequence of the elements.
  • static void sort(List list1, Comparator comp1): Sorts the elements of list1 according to the order set by the comparator object comp1.

The following program illustrates the usage of first algorithm sort(). The second one using comparator is given later. Here, ArrayList and HashSet elements are put in ascending order with Collections.sort() method.

ArrayList myList = new ArrayList();

An ArrayList object myList is created and added some elements with add() method inherited from Collection interface.

System.out.println(“After sort ArrayList: ” + myList);

The sort() method is applied to myList and now myList contains the elements in ascending order.

HashSet mySet = new HashSet();

A HashSet object mySet is created and added a few elements with add() method.

// Collections.sort(hs1); // ERROR

The above statement raises a compilation error as sort() method should be applied to List elements (see the above method signature) only and not on any other data structure.

List tempList = new ArrayList();

To do the job, the mySet elements are passed to a List object tempList and then sorted. This is how all the collection classes are interoperable.

TreeSet ts1 = new TreeSet(mySet);
System.out.println(“After sort HashSet using TreeSet: ” + ts1);

There is another easy way of sorting in natural order for Set elements. It is using the default nature of TreeSet. A TreeSet object ts1 is created and passed mySet elements at the time of ts1 object creation itself by passing to the constructor (without using addAll() method). TreeSet orders the elements implicitly. Observe the output screenshot.

Other Collections Methods

List Reversing Sorting

It is advised to read List Fundamentals before proceeding the following programs.

Four programs are given on List with different functionalities.

  1. List Methods: Uses frequently used methods like size(), add(), get(), contains(), indexOf(), lastIndexOf(), subList(), remove(), clear() and isEmpty().
  2. List Iteration: Comparing two lists with equals(), converting list elements to array with toArray(), printing array elements with foreach loop, printing list elements with Iterator (forward) and ListIterator (forward and backward).
  3. List Reversing Sorting: Reversing and sorting the list elements with methods asList(), sort(), reverseorder.
  4. List Unique Elements: Removing duplicate elements from list, sorting list elements, converting list to Set and again set to list.

In this third program, reversing and sorting of list elements is done with methods sort() and reverseOrder().

String countries[] = { “india”, “Bangladesh”, “nepal”, “Srilanka” };
List countryList =Arrays.asList(countries);

Java collections framework includes two classes Collections and Arrays. Collections is used to manipulate data structure elements and Arrays is used to manipulate array elements. asList(countries) method returns a list object countryList that contains the elements of the array countries.

System.out.println(“Case sensitive sorting: ” + countryList);
Collections.sort(countryList, String.CASE_INSENSITIVE_ORDER);

The sort() method of Collections sorts the elements in ascending order implicitly. But it makes case-sensitive order. To ignore the sensitivity, use a variable String.CASE_INSENSITIVE_ORDER.

Collections.sort(countryList, Collections.reverseOrder());

The sort() method with parameter reverseOrder() reverses the elements and sorts. The sorting affects the original elements itself.

All Iterators in a Nutshell

Enumeration Iterator
ListIterator Arrays foreach
Collections foreach Enumeration vs Iterator
Iterator vs ListIterator

General Exceptions raised by collections classes

IllegalStateException ConcurrentModificationException
UnsupportedOperationException NullPointerException