Sort ArrayList with Collections sort()

Sort 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.

Example on Sort ArrayList with Collections sort()

Sort ArrayList with Collections sort()
Output screenshot on Sort ArrayList with Collections sort()

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.

Similar method sort() exists in class Arrays also to sort array elements at Sorting array elements with sort().

Leave a Reply

Your email address will not be published. Required fields are marked *