How To Sort List In Ascending & Descending Order Using Java Stream API?

Introduction

Stream API feature was introduced in Java 8 but it is still confusing for many and also many have not even used it a single time. I will try to explain Java Stream concepts with simple examples in Learn Stream API in Java with Examples series.

In this post, we will learn to Sort List In Ascending & Descending Order Using Java Stream API i.e. sorted() method.

YouTube Tutorials

If you want to learn from a video tutorial then please refer to the below video –

Sort List In Ascending & Descending Order Using Java Stream API

Java stream provides a method sorted() which can sort List in ascending and descending order without you to write any complex logic. By default sorting() method sorts the list in ascending order. If we want to sort in descending order we need to pass Comparator.reverseOrder() in sorted() method as a parameter.

Java Program

package solveproblemswithsreams;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortListUsingJavaStreamAPI {
	
	public static void main(String[] args) {
		
		List unsortedList = Arrays.asList(10,1,21,3,6,2);
		// Sorting in natural order or ascending order
		List sortedListAsc = 
				unsortedList.stream()
					.sorted()
					.collect(Collectors.toList());
		
		System.out.println("Before sorting : "+ unsortedList);
		System.out.println("After sorting  : "+ sortedListAsc);
		
		// Sorting in descending order
		List sortedListDesc = 
				unsortedList.stream()
					.sorted(Comparator.reverseOrder())
					.collect(Collectors.toList());
		
		System.out.println("Before sorting : "+ unsortedList);
		System.out.println("After sorting  : "+ sortedListDesc);
	}
}

Output

Before sorting : [10, 1, 21, 3, 6, 2]
After sorting  : [1, 2, 3, 6, 10, 21]
Before sorting : [10, 1, 21, 3, 6, 2]
After sorting  : [21, 10, 6, 3, 2, 1]

GitHub Repo Link

https://github.com/amod-mahajan/MSE_LearnJavaStreamsWithExamples.git

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe to my YouTube channel.
#ThanksForReading
#HappyLearning

Leave a Reply

Your email address will not be published. Required fields are marked *