Java 8 Stream Sort List Sample

Let’s take a look at the Java 8 Stream sorted() sample tutorial. We can sort a stream (list, Set, Map, etc) in natural order as well as make use of the Comparator.

The sorted() method will sort the elements of stream using natural ordering. The Java 8 Comparator can be instantiated using a Lambda Expression.

Assuming jcdList is an instantiated list object, we can sort that list in a natural order.

jcdList.stream().sorted() 


Assuming jcdList is an instantiated list object, we can reverse the natural order using the Comparator reverseOrder() method.

jcdList.stream().sorted(Comparator.reverseOrder()) 


Let’s take a look at our sample code below. We create a list of String objects. Add elements to our list, in this case we used fruit. Now we can manipulate our Stream and sort the list naturally and then again but in reverse.

package com.jcd.java8.tutorials;

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

public class JavaSortStreamList {

	public static void main(String[] args) {

		//Create a list of Strings
		List<String> jcdList = new ArrayList<String>();
		
		//Add String to the list
		jcdList.add("Apple");
		jcdList.add("Banana");
		jcdList.add("Grapes");
		jcdList.add("Mano");
		jcdList.add("Orange");
		jcdList.add("Peach");

		//Sort naturally and print
		System.out.println("[Natural Sorting]");
		List<String> listNatural = jcdList.stream().sorted().collect(Collectors.toList());
		listNatural.forEach(e -> System.out.println("Fruit:"+e));
		
		//Sort naturally in reverse and print
		System.out.println("[Natural Sorting in Reverse]");
		List<String> listNaturalRev = jcdList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
		listNaturalRev.forEach(e -> System.out.println("Fruit:"+e));		
		
	}

}


After we run our Java program, the output looks like this…

[Natural Sorting]
Fruit:Apple
Fruit:Banana
Fruit:Grapes
Fruit:Mano
Fruit:Orange
Fruit:Peach
...
[Natural Sorting in Reverse]
Fruit:Peach
Fruit:Orange
Fruit:Mano
Fruit:Grapes
Fruit:Banana
Fruit:Apple


Add a Comment

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