使用反向比较器并对流进行排序时出现编译错误

问题描述 投票:0回答:3

我有以下清单:

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

我想按

course.length()
对此列表进行排序,但必须颠倒过来。这是预期的输出:

Microservices
Spring Boot
Kubernetes
Docker
Spring
Azure
PCF
AWS
API

这是我正在处理的代码行,但它不起作用:

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

如何实现我想要的排序顺序?

java sorting lambda java-stream reverse
3个回答
3
投票

我们可以使用的一个技巧是在排序时使用字符串长度的负值:

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

打印:

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

0
投票

Java 类型系统无法推断

word
中的
Comparator.comparing
String
,或者同等地推断
Comparator.comparing(word -> word.length())
应该是
Comparator<String>

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

这里的修复是让事情变得更加明确,以便编译器最终得到正确的类型,而不是依赖 Java 的类型推断算法。 有多种方法可以做到这一点;以下是其中一些:

courses.stream().sorted(
        Comparator.comparing((String word) -> word.length()).reversed());
courses.stream().sorted(
        Comparator.comparing(String::length).reversed());
Comparator<String> wordLengthComparator = 
        Comparator.comparing(word -> word.length());
courses.stream().sorted(
        wordLengthComparator.reversed());
courses.stream().sorted(
        Comparator.<String, Integer>comparing(word -> word.length()).reversed());
courses.stream().sorted(
        Comparator.comparing(
                (Function<String, Integer>) (word -> word.length())).reversed());

-1
投票

Reversed 返回类型为

Object
的对象。你需要一个演员:

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);
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.