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

Convert String to Date Using java.util.Calendar

The java.util.Calendar class also encapsulates a date. The Calendar class has some more features than the java.util.Date class. It provides the ability to extract...

How To Convert String To Date in Java

Introduction There are often scenarios in programming, where you will need to convert a date in String format to an actual Date object. For example,...

Java Tutorial #3 – Java Arrays

Table of Contents One Dimensional Array Declaring Array Allocting Memory to Array Accessing Array Elements Initializing Array Length of Array Multi Dimensional Array Creating 3...

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

Â

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

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

Rounding Decimal Number With Java DecimalFormat

The DecimalFormat class has a method called setRoundingMode() which can be used for setting the rounding mode for DecimalFormat object. The setRoundingMode() accepts RoundingMode...

Format Decimal Numbers Using Locale

If you want to create a DecimalFormat instance for a specific Locale, create a NumberFormat and cast it to a DecimalFormat. The java.text.DecimalFormat class is...

Java Tutorial #4 – Control Statements

Introduction Control statements are used to change the flow of execution based on changes to certain variables in the code. One of the types of...

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