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.

One thought on “Understanding string list sorting in Java

  1. Pingback: Sorting string list in ascending and descending order in Java | muthutechno

Leave a comment