Can we sort a list with Lambda in Java?


Yes, we can sort a list with Lambda. Let us first create a String List:

List<String> list = Arrays.asList("LCD","Laptop", "Mobile", "Device", "LED", "Tablet");

Now, sort using Lambda, wherein we will be using compareTo():

Collections.sort(list, (String str1, String str2) -> str2.compareTo(str1));

The following is an example to sort a list with Lambda in Java:

Example

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String... args) {  
      List<String> list = Arrays.asList("LCD","Laptop", "Mobile", "Device", "LED", "Tablet");
      System.out.println("List = "+list);
      Collections.sort(list, (String str1, String str2) -> str2.compareTo(str1));
      System.out.println("Sorted List = "+list);
   }
}

Output

List = [LCD, Laptop, Mobile, Device, LED, Tablet]
Sorted List = [Tablet, Mobile, Laptop, LED, LCD, Device]

Updated on: 30-Jul-2019

597 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements