Java 8 Program to Sort a List Using compareTo() and Method Reference

Here we can Sort a List Using compareTo() and Method Reference.

  • In this example, we will sort a List<Integer> in Java using the  Collections.sort() method.
  • First, we use a lambda expression with the compareTo() method.
  • Then, we use a method reference to sort the list in a shorter and cleaner way.
  • Both approaches produce the same sorted output.
				
					import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SortWithCompareTo {
	public static void main(String[] args) {
		List<Integer> list = Arrays.asList(15, 24, 40, 2, 19);
		
        //Method 1: Sorting using lambda expression:-
		System.out.println("Sorting with lambda expression and compareTo():- ");
		Collections.sort(list, (n1, n2) -> n1.compareTo(n2));
		list.forEach(System.out::println);
		
        //ethod 2: Sorting using method reference:-
		System.out.println("Sorting with Method Reference and compareTo():- ");
		Collections.sort(list, Integer::compareTo);
		list.forEach(System.out::println);
	}
}
				
			

Output :-
Sorting with lambda expression and compareTo():-
2
15
19
24
40
Sorting with Method Reference and compareTo():-
2
15
19
24
40

FAQ

Why can we use Integer::compareTo directly?

Integer::compareTo is a method reference to the compareTo() instance method of the Integer class.It is used as a comparator in Collections.sort() to compare two integer values in ascending order.