Home > database >  customize sorted ordered by reverse Java
customize sorted ordered by reverse Java

Time:06-06

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())

I really appreciate if someone can give a hand.

CodePudding user response:

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]

CodePudding user response:

Reversed returns an object of type Object. You'll need a cast:

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class App {
  public static void main(String[] args) throws Exception {
    List<String> courses = List.of("Spring", "Spring Boot", "API", "Microservices", "AWS", "PCF", "Azure", "Docker", "Kubernetes");

    courses = courses.stream().sorted(Comparator.comparingInt(x -> ((String) x).length()).thenComparing(Comparator.comparing(x -> x.toString())).reversed()).collect(Collectors.toList());

    courses.stream().forEach(System.out::println);
  }
}

  • Related