javasortinglambdajava-streamreverse

Compilation error when using a reversed comparator and sorting a stream


I have the following list:

List<String> courses = List.of("Spring", "Spring Boot", "API", "Microservices",
            "AWS", "PCF", "Azure", "Docker", "Kubernetes");

I want to sort this list by the course.length(), but it has to be reversed. This is the excpected output:

Microservices
Spring Boot
Kubernetes
Docker
Spring
Azure
PCF
AWS
API

This is the line of code that I'm working on, but it does not work:

courses.stream().sorted(Comparator.comparing(word -> word.length()).reversed())

How can I achieve my desired sort order?


Solution

  • One trick we can use here is to use the negative value of the string length when sorting:

    List<String> courses = List.of("Spring", "Spring Boot", "API", "Microservices",
        "AWS", "PCF", "Azure", "Docker", "Kubernetes");
    courses = courses.stream().sorted(Comparator.comparing(word -> -1.0*word.length())).collect(Collectors.toList());
    System.out.println(courses);
    

    This prints:

    [Microservices, Spring Boot, Kubernetes, Spring, Docker, Azure, API, AWS, PCF]