Java List Sort

In this tutorial, we will learn about java collection list sorting and its syntax along with working examples of it which includes user-defined class sort.

List Sort

In Java, List collection guarantees insertion order but while coming to sort the list, it requires whether sorting should follow natural order or reverse order or custom order. We have in-built sorting without implementing custom sorting order but almost all follows natural order for example elements type like String, Integer etc, these are implemented sort with natural order only.

List allows to add user-defined class elements into the collection, to sort user-defined elements will be difficult because not sure which data-member sort is required. So, we need to specify custom order logic based on need using Comparator implemented class or implementing Comparable interface on user-defined class itself.

The major difference from Comparable to Comparator, Comparable should be implemented by the Element class itself whereas Comparator can be implemented by any class. This gives flexibility of comparing based on the user request or it can be done based on different data-members of element class.

For simple sorting, we can use inbuilt utility class java.util.Collections under collections framework which allows to sort elements of user-defined as well and allows to sort reverse order also. In case of more complex sorting can be achieved using custom Comparator implementation.

We will explore from the inbuilt sort to custom sorting, will start from syntax and working examples. In the examples, will cover natural, reverse sorts and custom user-defined sorting also.

Sort Types:

  1. Natural order sort.
  2. Reverse order sort.

Natural order sort for list:

Natural order follows ascending order, natural order of list elements can be done for the custom class and for an inbuilt class object.

Syntax:

//Inbuilt method of sort from List
list.sort(null);
//For elements which implemented Comparable interface 
Collections.sort(List<T> list)
//For elements which not implemented Comparable interface 
Collections.sort(List<T> list, Comparator<? super T> c)

Reverse order list sort:

Reverse order follows descending order, like natural order list elements sorting can be done in reverse order.

Syntax:

//For elements which implemented Comparable interface 
Collections.sort(List<T> list, Collections.reverseOrder()) (or) list.sort(Collections.reverseOrder());
//For elements which not implemented Comparable interface 
Collections.sort(List<T> list,  Collections.reverseOrder(Comparator<? super T> c)) (or) list.sort(Comparator<? super T> c)

List sort example with natural and reverse order of in-built class objects

In this example, we will sort the list elements on both natural and reverse order on a in-built class.

CopiedCopy Code
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class ListSortExample {
	public static void main(String[] args) {
		List<String> fruits = new LinkedList<>();
		// Adding fruits to the list
		fruits.add("Orange");
		fruits.add("Mango");
		fruits.add("Apple");
		fruits.add("Banana");
		System.out.println("List ordered before sort: "+fruits.toString());
		//sort using inbuilt method without comparator
		fruits.sort(null);
		// After sort
		System.out.println("List ordered natural sort: "+fruits.toString());
		//sort using with comparator for reverse order
		fruits.sort(Collections.reverseOrder());
		//Sort reverse to the natural order
		System.out.println("List ordered reverse sort: "+fruits.toString());
	}
}

Output :

List ordered before sort: [Orange, Mango, Apple, Banana]
List ordered natural sort: [Apple, Banana, Mango, Orange]
List ordered reverse sort: [Orange, Mango, Banana, Apple]

Explanation :

In the above example, we have created a List object with element type as String. Added four elements to the list, invoke sorting with null comparator but it works without runtime exception as String class implemented the Comparable interface and this follows natural order, finally printed content to the console.

Later, we passed Comparator for reverse order of String elements and printed all elements of List.

List sort example with natural and reverse order of custom class objects

In this example, we will use user-defined or custom class objects for sorting by choosing any of the user-defined class data-members.

CopiedCopy Code
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class UserdefinedSortExample {
	public static void main(String[] args) {
		// Created a list with element type Student
		List<Student> list = new LinkedList<Student>();
		Student std1 = new Student("A1", 90);
		Student std2 = new Student("A2", 75);
		Student std3 = new Student("A3", 85);
		Student std4 = new Student("A4", 79);
		// Added four elements
		list.add(std1);
		list.add(std2);
		list.add(std3);
		list.add(std4);
		// Must pass comparator as Student class not implemented Comparable
		// Comparator implementation for sort based on marks
		list.sort(new Comparator<Student>() {
			@Override
			public int compare(UserdefinedSortExample.Student o1, UserdefinedSortExample.Student o2) {
				// we are comparing o2 with o1 to have highest marks first
				return o2.stdMarks.compareTo(o1.stdMarks);
			}
		});
		// student list after marks wise sort
		System.out.println(list);
		// Comparator implementation for sort based on name
		list.sort(new Comparator<Student>() {
			@Override
			public int compare(UserdefinedSortExample.Student o1, UserdefinedSortExample.Student o2) {
				return o1.stdName.compareTo(o2.stdName);
			}
		});
		// student list after name wise sort
		System.out.println(list);
	}
	static class Student {
		public String stdName;
		public Integer stdMarks;
		public Student(String stdId, int stdMarks) {
			this.stdName = stdId;
			this.stdMarks = stdMarks;
		}
		@Override
		public String toString() {
			return "Student [stdName=" + stdName + ", stdMarks=" + stdMarks + "]";
		}
	}
}

Output :

[Student [stdName=A1, stdMarks=90], Student [stdName=A3, stdMarks=85], Student [stdName=A4, stdMarks=79], Student [stdName=A2, stdMarks=75]]
[Student [stdName=A1, stdMarks=90], Student [stdName=A2, stdMarks=75], Student [stdName=A3, stdMarks=85], Student [stdName=A4, stdMarks=79]]

Explanation :

In the above example, we have created two Comparators for user-defined data-members sort, one for student marks sorting from highest to lowest and another one for student name with alphabetical or natural order.

Conclusion:

In this tutorial, we have covered List sorting including syntax along with the working example including user-defined or custom sort.