Can we sort a list with Lambda in Java?

Java 8Object Oriented ProgrammingProgramming

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]
raja
Published on 02-May-2019 10:10:22
Advertisements