在Java 8中对比较器的误解
public class Test { public static void main(String[] args) { List<Pair> list = new ArrayList(); list.add(new Pair("1", 8)); list.add(new Pair("3", 2)); list.add(new Pair("2", 15)); list.stream() .sorted(Comparator.comparingInt(p -> pv)) .map(p -> pk) .forEach(System.out::println); } } class Pair { K k; V v; public Pair(K k, V v) { this.k = k; this.v = v; } }
好吧,正如你所知,这段代码是从与最高值相关的最低值打印我的对键,所以我得到了预期的输出:
3 1 2
到现在为止还挺好。 现在我想反过来,我想我只需要这样做
list.stream() .sorted(Comparator.comparingInt(p -> pv).reversed()) .map(p -> pk) .forEach(System.out::println);
但是我收到了编译错误:
v cannot be resolved or is not a field
所以看起来comparingInt
正在返回一个Comparator
。 为什么会这样? 它不应该返回Comparator
吗?
这些都可以使用Eclipse Luna版本1和javac进行再现。
javac -version => 1.8.0 java -version => java version "1.8.0_25"
哦也随意更改我的问题的标题是你发现它太一般,但我找不到正确的条款
我认为只是类型推断失败,基本上 – 因为reverse()
调用阻碍了sorted()
和lambda表达式的预期参数类型。
如果您明确指定compareInt类型,则可以执行此操作:
list.stream() .sorted(Comparator.>comparingInt(p -> pv).reversed()) .map(p -> pk) .forEach(System.out::println);
或者,如果您只是先声明比较器:
Comparator> forward = Comparator.comparingInt(p -> pv); list.stream() .sorted(forward.reversed()) .map(p -> pk) .forEach(System.out::println);
我觉得应该有一个Stream.reverseSorted
所以让这种事情变得非常容易,但它看起来并不存在:(