Misunderstanding about Comparator in java 8

别等时光非礼了梦想. 提交于 2019-12-01 02:54:28

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.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!