在Java 8中对比较器的误解 [英] Misunderstanding about Comparator in java 8

查看:133
本文介绍了在Java 8中对比较器的误解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Test {
    public static void main(String[] args) {
        List<Pair<String, Integer>> 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 -> p.v))
            .map(p -> p.k)
            .forEach(System.out::println);

    }
}

class Pair<K, V> {
    K k;
    V v;
    public Pair(K k, V v) {
        this.k = k;
        this.v = v;
    }
}

好的,你知道这段代码正在打印我的一对从最高值关联到最高值的键,所以我得到预期的输出:

Ok, as you understood this code is printing my pair keys from the lowest value associated to the highest so I get the expected output:

3
1
2

3 1 2

到目前为止一切顺利。现在我想做相反的事情,我想我只需要这样做

So far so good. Now I wanted to do the reverse, I thought I would only have to do

list.stream()
    .sorted(Comparator.comparingInt(p -> p.v).reversed())
    .map(p -> p.k)
    .forEach(System.out::println);

但我收到编译错误:

v cannot be resolved or is not a field

所以它似乎 comparisonInt 返回 Comparator< Object> 。为什么会这样?它不应该返回 Comparator< Integer>

So it seems like comparingInt is returning a Comparator<Object>. Why it so? Shouldn't it return a Comparator<Integer> ?

这些都可以使用Eclipse Luna版本1和javac重现。

These are both reproductible with Eclipse Luna version 1 and javac.

javac -version => 1.8.0
java  -version => java version "1.8.0_25"

哦也随意更改我的问题的标题你找到了它太笼统了,但我找不到正确的术语

Oh also feel free to change the title of my question is you find it too general, but I couldn't find the correct terms

推荐答案

我认为这种类型推断是失败的,基本上 - 因为 reverse()调用会妨碍预期的参数类型 sorted()和lambda表达式。

I believe it's just that type inference is failing, basically - because the reverse() call gets in the way of the expected argument type of sorted() and the lambda expression.

如果您明确指定类型为 comparisonInt ,则可以这样做:

You can do it if you specify the type to comparingInt explicitly:

list.stream()
    .sorted(Comparator.<Pair<String, Integer>>comparingInt(p -> p.v).reversed())
    .map(p -> p.k)
    .forEach(System.out::println);

或者如果您只是先声明比较器:

Or if you just declare the comparer first:

Comparator<Pair<String, Integer>> forward = Comparator.comparingInt(p -> p.v);
list.stream()
    .sorted(forward.reversed())
    .map(p -> p.k)
    .forEach(System.out::println);

我觉得应该有一个 Stream.reverseSorted 所以让这类事情变得非常简单,但它看起来并不存在:(

It feels to me like there should be a Stream.reverseSorted so make this sort of thing really easy, but it doesn't look like it exists :(

这篇关于在Java 8中对比较器的误解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆