java program sorting with compareTo and method reference method?

Here we sort with collections.sort method.in this we pass value with lambda to compareTo method.In second method we pass list of data to Integer Object with method reference to compareTo method.

				
					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 one:-
		System.out.println("sorting with lambda expression and compareTo:- ");
		Collections.sort(list, (n1, n2) -> n1.compareTo(n2));
		list.forEach(System.out::println);
		
        //Method two:-
		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

Leave a Comment

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