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 String.join()

Java 8 has added a static join method to the String class. This concatenates Strings using a delimiter. Performance wise, it is similar to...

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...

Convert List to Array Using Stream with Param

There is an overloaded version of the Stream.toArray method which can be used to return a result array that is of the same data...

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...

Â

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

VBS Part 1 – Introduction and Background

At the upfront, this theoretical article might look boring to most of us but still, it is advisable to know about our scripting friend...

How To Create Maven Project in Eclipse With Archetype

Maven Basics Maven automates the steps involved in building a software application like adding the JAR files, compiling code, running unit tests, creating the output...

Format Decimal Numbers with Grouping Separator

The DecimalFormat class has a method called setGroupingSize() which sets how many digits of the integer part to group. Groups are separated by the...

How To Change Font for Eclipse Editor Pane

This article shows how to change the text size and style for the Eclipse editor pane. The font used for Eclipse editor pane can be...

CHECKOUT TUTORIALS

Working with JMeter Listeners

About Listeners Listeners are used for displaying test results in JMeter. Listeners allow system engineers to analyze the responses from the testing system and monetize...
- Advertisement -spot_img