How to Sort an ArrayList of Strings

To sort an ArrayList of Strings, we will use Collections class. Collections class in java.util consists of static methods written using polymorphic algorithms that process given collection and return a new collection.

Below we discuss two variants of the sort method. Both sort methods require collection of objects that implement the Comparable interface providing the implementation of compareTo method.

Collections.sort(List) – to sort the ArrayList in ascending order:
Collections.sort(list);

Collections class provides a sort method which accepts List as the only argument.

Collections.sort(List, Comparator) – to sort an ArrayList in descending order:
Collections.sort(list, Collections.reverseOrder());

Collections class also provides a sort method which accepts a Comparator as its second argument which can be used to define its own order. However, in this example, we are using Collections.reverseOrder, which returns a Comparator that orders a list in reverse order.

Example:
package com.techstackjournal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortingArrayList {

	public static void main(String[] args) {

		List<String> list = new ArrayList<>();
		list.add("Jack Nicholson");
		list.add("Robert De Niro");
		list.add("Al Pacino");
		list.add("Tom Hanks");

		System.out.println("*** BEFORE SORTING ***");
		for (String string : list) {
			System.out.println(string);
		}

		Collections.sort(list);

		System.out.println();
		System.out.println("*** AFTER SORTING LIST BY ASCENDING ORDER ***");
		for (String string : list) {
			System.out.println(string);
		}

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

		System.out.println();
		System.out.println("*** AFTER SORTING LIST BY DESCENDING ORDER ***");
		for (String string : list) {
			System.out.println(string);
		}

	}

}
Output:
*** BEFORE SORTING ***
Jack Nicholson
Robert De Niro
Al Pacino
Tom Hanks

*** AFTER SORTING LIST BY ASCENDING ORDER ***
Al Pacino
Jack Nicholson
Robert De Niro
Tom Hanks

*** AFTER SORTING LIST BY DESCENDING ORDER ***
Tom Hanks
Robert De Niro
Jack Nicholson
Al Pacino

Leave a Comment