How To Sort List in Java

Using Collections.sort, List.sort and Stream API

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.

Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

RELATED POSTS

Concatenate Strings Using StringBuilder.append()

In addition to String, Java has the java.lang.StringBuffer and java.lang.StringBuilder classes. These can also be used to concatenate Strings. The advantage of these...

Format Decimal Numbers Using Pattern

The java.text.DecimalFormat class is used to format numbers using a user specified formatting. This concrete subclass of NumberFormat, allows formatting decimal numbers via predefined...

What is In-Proc and Out-Proc (COM) ?

The terms 'In-Proc' and 'Out-Proc' are to describe the kind of implementation of COM Servers. Before we begin, for those who are not quite...

Concatenate Strings Using String.concat()

The String class has a method called concat. It accepts as parameter a String value and concatenates it with the current String. The following...

Â

RECENT 'HOW-TO'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string with a function or variable. It does not...

MORE ON CODEX

MORE IN THIS CATEGORY

How To Convert List To Array in Java

A common scenario faced by programmers is to convert a Java List to an Array. A 'List' is part of the Collection Framework and...

Concatenate Strings Using Plus Operator

In Java, a String is a sequence of characters. There are often programming situations where you will need to concatenate Strings. There are several...

How To Install Pacman For Git on Windows

The 'Git for Windows' by default does not come with MSYS2 package manager called 'Pacman' and hence it is a limited version or subset...

Concatenate Strings Using String Joiner

Java 8 has added a new class called StringJoiner. This concatenates Strings using a delimiter as well as adds a prefix and suffix to...

CHECKOUT TUTORIALS

Java Tutorial #7 Part 1 – Classes & Objects

Classes are a very important concept in Java. Java code always needs to be written in a class. In this article, we will be...
- Advertisement -spot_img