How to sort a List in Java 8 using Lambda

In Java 8, a List can be sorted with a Lamdba expression instead of using an anonymous Comparator.

Syntax:

list.sort( (a, b) -> a.compareTo( b ) );

This example creates a list of random integers. That list is printed in the output to show the order. Then, the list is sorted calling the sort method of the instance object. It is passing a comparator as a parameter. That list is written in the output to show that the values of the list have been sorted correctly.

Create the following java file:

import java.util.Arrays;
import java.util.List;

public class LambdaListSort {

	public static void main(String[] argv){

		// Create an unsorted List 
		List<Integer> list = Arrays.asList( 1, 4, 2, 3, 0 ); 

		System.out.println( "Unsorted List:" + list);

		// Sort the list
		list.sort( (a, b) -> a.compareTo( b ) );

		System.out.println( "Sorted List:" + list);
	}
	
}

The output will be:

Unsorted List:[1, 4, 2, 3, 0]
Sorted List:[0, 1, 2, 3, 4]

The same way we call the sort method in the previous example, we can call the Collections sort method with an Object implementing the Comparable interface. The all the elements of the list must implement Comparable and are sorted into ascending order.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LambdaListSort2 {

	public static void main(String[] argv){

		// Create an unsorted List 
		List<Integer> list = Arrays.asList( 1, 4, 2, 3, 0 ); 

		System.out.println( "Unsorted List:" + list);

		// Sort the list
		Collections.sort( list, (a, b) -> a.compareTo( b ) );

		System.out.println( "Sorted List:" + list);
	}
	
}

The output will be:

Unsorted List:[1, 4, 2, 3, 0]
Sorted List:[0, 1, 2, 3, 4]

The code is very simple and save the time to create an anonymus comparator. The sort method can be used on any list implementation like an ArrayList or a LinkedList.

References:

Lambda Expressions

Recent Comments