Sorting string list in ascending and descending order in Java

Sorting string list in ascending order in Java is straight forward.

Below code will sort string list in ascending order,

	public static void main(String[] args){

		List<String> stringList = new ArrayList<>();
		stringList.add("Suzuki");
		stringList.add("Honda");
		stringList.add("Toyota");
		stringList.add("Ford");
		stringList.add("Renault");
		stringList.add("Hyundai");

		// before sorting
		System.out.println(stringList);

		// sort the list
		Collections.sort(stringList);

		// after sorting
		System.out.println(stringList);
	}
// before sorting
[Suzuki, Honda, Toyota, Ford, Renault, Hyundai]

// after sorting
[Ford, Honda, Hyundai, Renault, Suzuki, Toyota]

Here I’m adding car company names to string list and passing it to Collections sort method. The sort method will sort string list items in ascending order. Notice that sort method will return void, instead it will manipulate the original list object that we passed to it so when we print the list object, string items are printed in ascending order.

But sorting string list in descending order is not straight forward as ascending order. To understand sorting in descending order first we need to understand how sorting mechanism work. To understand sorting mechanism please go through my another post Understanding string list sorting in Java.

To sort string list in descending order we have to use overloaded sort method of Collections class.

public static <T> void sort(List<T> list, Comparator<? super T> c)

It takes two parameters, list to be sorted and comparator object. Comparator object is the object where our sorting logic resides. First we need to write our own Comparator class where our sorting logic resides for string sorting and then pass its object to sort method

public class MyComparator implements Comparator<String>{
		@Override
		public int compare(String o1, String o2) {
			return o2.compareTo(o1); // magic line
		}
	}

The highlighted line in the above code is where all the magic happens. This line is responsible for sorting list in ascending and descending order. o2.compareTo(o1) will make sort method to sort list in descending order but If we change it to o1.compareTo(o2) then list will be sorted in ascending order.

Now pass MyComparator object to sort method along with string list to be sorted and run the code.

	public static void main(String[] args){

		List<String> stringList = new ArrayList<>();
		stringList.add("Suzuki");
		stringList.add("Honda");
		stringList.add("Toyota");
		stringList.add("Ford");
		stringList.add("Renault");
		stringList.add("Hyundai");

		// before sorting
		System.out.println(stringList);

		// sort the list
		MyComparator myComparator = new MyComparator();
		Collections.sort(stringList, myComparator);

		// after sorting
		System.out.println(stringList);
	}
// before sorting
[Suzuki, Honda, Toyota, Ford, Renault, Hyundai]

// after sorting
[Toyota, Suzuki, Renault, Hyundai, Honda, Ford]

Notice that string list items are printed in descending order.

Here is the helper method you can use for sorting string list in ascending and descending order,

	public void listSortEx(List<String> list, final Boolean descOrder){
		Collections.sort(list, new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {
				if(descOrder){
					return o2.compareTo(o1);
				}else{
					return o1.compareTo(o2);
				}
			}
		});
	}

Using this method is easy. Just pass it a string list to be sorted and a boolean value true if you want to sort list in descending order or false to sort list in ascending order. Notice that this function will return void, so the original list object you pass will be manipulated instead.

Understanding string list sorting in Java

Sorting in Java is not straight forward as we think. It has got its own mechanism to sort the list we provide. Here is the example for String sorting in Java,

	public static void main(String[] args){

		List<String> stringList = new ArrayList<>();
		stringList.add("Suzuki");
		stringList.add("Honda");
		stringList.add("Toyota");
		stringList.add("Ford");
		stringList.add("Renault");
		stringList.add("Hyundai");

		// before sorting
		System.out.println(stringList);

		// sort the list
		Collections.sort(stringList);

		// after sorting
		System.out.println(stringList);

	}

[Suzuki, Honda, Toyota, Ford, Renault, Hyundai]
[Ford, Honda, Hyundai, Renault, Suzuki, Toyota]

Here I’m adding car company names to ArrayList. When I print the list without sorting, company names are printed in the order I added to the list. When I print the list after sorting, company names are printed in alphabetical order.

Based on the sorted output, two questions comes to our mind Who decides on the sorting order of the String and Why strings are sorted in ascending alphabetical order and why not descending alphabetical order. Let me answer these questions.

When we look at Collections sort method declaration in Java docs this is what it says,

public static <T extends Comparable<? super T>> void sort(List<T> list)

Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface.

When it says all elements in list must implement Comparable interface, In our case it means String class should should implement Comparable interface since we are using String list.

Here is the String class declaration which implement Comparable Interface as per Java docs.

public final class String extends Object implements Serializable, Comparable<String>, CharSequence

Comparable interface has one only method compareTo(T o) which all implementing classes should implement. Since String class implements Comparable interface so it should implement compareTo method. The compareTo method will be invoked on all String objects in the list one by one by passing other String object as its argument during sorting. This method will return either negative number or positive number or zero based on the comparison result of two objects.

int compareTo(T o){
	// compare current object with o
}
  • If current object is greater than o -> positive number is returned
  • If current object is smaller than o -> negative number is returned
  • If current object is equal to o -> zero is returned

Based on the return value sorting of object takes place inside the sort method. For Strings, logic for comparing String objects is already written in its compareTo method so we don’t have to worry about it.