Site icon Automation Dojos

How To Sort List in Java

Table of Contents

Introduction

A List is an interface in the Java collection framework. It can be used to store objects. Programmers often encounter scenarios where they need to sort a List. There are several ways you can achieve this. In the next few sections, I will be going over each method in detail.

1. Using Collections.sort

The Collection framework has the java.util.Collections class. This has a lot of utility methods that can be used to perform various operations on Collections. One of these is the Collections.sort method. There are two overloaded versions of this method as explained below.

Collections.sort without Comparator

This version of the Collections.sort method accepts as parameter a List object. It sorts the List according to the natural order of the elements in the List. The following code demonstrates this:

public static void usingCollectionsSort() {
List<Integer> input = Arrays.asList(34,12,67,8,91,54,24);
Collections.sort(input);
System.out.print("Sorted List:");
input.forEach(num -> System.out.print(num+" "));
}

Here, the code creates a new List with some Integer values. As you can see this List is not sorted. The code then invokes the Collections.sort method. Since the natural ordering for Integers is ascending order, this sorts the List in ascending order. So, this code prints the following output:

Sorted List:8 12 24 34 54 67 91 

Collections.sort with Comparator

There is an overloaded version of the Collections.sort method. In addition to the List to be sorted, this method also accepts as parameter a Comparator. It then sorts the input List as per the specified Comparator. The following code demonstrates this:

public static void usingCollectionsSortWithComparator() {
List<Integer> input = Arrays.asList(34,12,67,8,91,54,24);
Collections.sort(input,(num1,num2) -> num2-num1);
System.out.print("Sorted List:");
input.forEach(num -> System.out.print(num+" "));
}

As before, this code creates an unsorted List with some values. The Collections.sort method is invoked with the input List and a lambda expression that implements the Comparator interface. Here, the lambda expression returns the difference of subtracting the first number from the second number. So, this is equivalent to sorting the List in descending order. So, this code prints the following output:

Sorted List:91 67 54 34 24 12 8

2. Using List.sort

Java 8 has added a sort method on the List interface. This can also be used to sort a List. It accepts as parameter a Comparator instance and sorts the List based on the specified Comparator. The following code demonstrates this:

public static void usingListSortWithStrings() {
List<String> input = Arrays.asList("Horse","Cat","Elephant","Giraffe");
	input.sort((str1,str2) -> str1.compareTo(str2));
	System.out.print("Sorted List:");
	input.forEach(num -> System.out.print(num+" "));

}

In this case, the code creates a List of String values. The List.sort method is invoked using a lambda expression that compares the Strings and returns the result of comparison. This is equivalent to sorting the List in alphabetical order. So, this code prints the following output:

Sorted List:Cat Elephant Giraffe Horse

List.sort has better performance compared to Collections.sort. This is because Collections.sort sorts the List by dumping its contents in an array. List.sort on the other hands sorts inline.

3. Using Stream API

The Stream API added by Java 8 can also be used to perform several operations on Collections. The Stream interface has a method called sorted that sorts the element in the Stream as per their natural order.  The following code demonstrates this:

public static void usingStreamSort() {
	List<Integer> input = Arrays.asList(34,12,67,8,91,54,24);
	Stream<Integer> inputStream = input.stream();
	Stream<Integer> sortedStream = inputStream.sorted();
	List<Integer> output = sortedStream.collect(Collectors.toList());
	System.out.print("Sorted List:");
	output.forEach(num -> System.out.print(num+" "));
}

Here, first the stream() method is invoked on the input List. This returns a Stream corresponding to the List. Then the sorted() method is invoked on the Stream. This returns a new Stream that is sorted. Finally, the collect() method is invoked which converts the Stream to a List back. So, this code prints the same output as before:

Sorted List:8 12 24 34 54 67 91

There is also an overloaded version of the sorted method that accepts as parameter a Comparator instance and sorts the input Stream as per the specified Comparator.

4. Sorting a List of Objects

Sometimes, you may have a List of objects and you may need to sort it based on some field in the class. You can achieve this by using a Comparator and either the Collections.sort of List.sort method.

For example, suppose you have a Student class as follows:

public class Student {
	
	private String name;
	private double marks;
	//constructors, getters and setters
}

And suppose you have a List of Student objects that need to be sorted based on the marks field. You can do this using the following code:

List<Student> input = new ArrayList<Student>();
		
input.add(new Student("Bill",76));
input.add(new Student("Jane",94));
input.add(new Student("George",68));
	
input.sort((s1,s2) -> s1.getMarks() - s2.getMarks());
System.out.print("Sorted List:");
input.forEach(s -> System.out.print(s.getName()+" "));

Here, we have used the List.sort method. The lambda expression passed to the sort method implements a Comparator and compares the marks fields. So, this code prints the following output: Sorted List:George Bill Jane

Conclusion

So, there are several ways in which you can sort a List in Java. You can use the Collections.sort to sort as per the natural order or using a custom Comparator. You can use the List.sort with a custom Comparator as well. You can also use the Stream API to sort a List.

Exit mobile version