Java Program to sort String Stream with reversed Comparator

Java 8Object Oriented ProgrammingProgramming

Let us first create a String List:

List<String> list = Arrays.asList("Tom", "Jack", "Ryan", "Kevin", "Loki", "Thor");

Now compare each element for reverse:

Comparator<String> comp = (aName, bName) -> aName.compareTo(bName);

Now, perform sort:

list.stream().sorted(comp.reversed())

The following is an example to sort String Stream with reversed Comparator:

Example

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List<String> list = Arrays.asList("Tom", "Jack", "Ryan", "Kevin", "Loki", "Thor");
      System.out.println("Initial List = "+list);
      System.out.println("Reverse...");
      Comparator<String> comp = (aName, bName) -> aName.compareTo(bName);
      list.stream().sorted(comp.reversed()) .forEach(System.out::println);
   }
}

Output

Initial List = [Tom, Jack, Ryan, Kevin, Loki, Thor]
Reverse...
Tom
Thor
Ryan
Loki
Kevin
Jack
raja
Published on 03-May-2019 10:52:28
Advertisements