Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

customize sorted ordered by reverse Java

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

I really appreciate if someone can give a hand.

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading