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

Remove Duplicates from List Using LinkedHashSet

Another implementation of the Set interface is LinkedHashSet. LinkedHashSet maintains the order of elements and helps to overcome the HashSet limitation. The following code...

How To Concatenate Strings in Java

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

Java Tutorial #2 – Operators in Java

Table of Contents Introduction 1. Assignment Operator 2. Arithmetic Operators 3. Compound Operators 4. Increment & Decrement Operators 5. Relational Operators 6. Logical Operators Introduction Operators are an essential...

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

Remove Duplicates from List Using Stream

Java 8 has added the Stream API that helps to easily perform bulk operations on Collections. A new method called stream() method has been...

How To Do API Testing with JMeter

Introduction Application Programming Interface is a very popular term among developers. It is simply a request provider that responds to your request. In other words,...

Java DecimalFormat Class

When you need to format decimal numbers, such as taking three or two decimal places for a number, showing only the integer part of...

Convert List to Array Using ToArray Without Param

Java provides a toArray method on the 'List' interface. This can be used to convert a 'List' to an array. Since there are are...

CHECKOUT TUTORIALS

Java Tutorial #2 – Operators in Java

Table of Contents Introduction 1. Assignment Operator 2. Arithmetic Operators 3. Compound Operators 4. Increment & Decrement Operators 5. Relational Operators 6. Logical Operators Introduction Operators are an essential...
- Advertisement -spot_img