首页 > 解决方案 > java流sort()对象到整数的下降集失败

问题描述

我有以下内容:

列出 someObjectList(里面的一个变量是 PosgreSQL 已经将年份排序为 DESC)

让我们说从 2018 年到 2016 年(我需要它作为设置,因为许多 someObject 包含相同的年份值,我只需要 DESC 顺序中的唯一值

我把它放在 Stream 中,如下所示:

Set<Integer> yearsSet = someObjectList.stream()
   .map(SomeObject::getYears)
   .collect(Collectors.toSet())

它返回集合,但 ASC 年份如 2016、2017、2018 与开头的 objectsList ([0].getYears()>2018, [1].getYears()> 2017...等) 不同

我还以两种方式使用了以下 .sort() 方法:

someObjectList.stream().map(SomeObject::getYears)
           .sorted(Comparator.comparing(Integer::intValue).reversed())
           .collect(Collectors.toSet())

someObjectList.stream().map(SomeObject::getYears)
            .sorted(Comparator.comparing(Integer::intValue))
            .collect(Collectors.toSet())

两者都没有做(也许我用Integer::intValue错了)?

然后我找到了一个丑陋的解决方案(在这里我得到了列表,但没关系,因为没有收到重复的内容):

someObjectList.stream().map(SomeObject::getYears)
            .collect(Collectors.toSet())
            .stream().sorted(Comparator.comparing(Integer::intValue).reversed())
            .collect(Collectors.toList())

它可以完成工作,但很丑陋。有什么建议我在哪里做错了,或者我该如何替换这个“香肠”部分?

我在某处读到地图不容易排序,也许它适用于集合?

感谢您的时间和建议

标签: javasortingintegersetjava-stream

解决方案


正如@axelh 所提到的,您不能订购一个集合(除非您选择 aTreeSet作为实现),所以这是一个解决方案,使用TreeSet并提供有问题的比较器作为构造函数的参数:

final Set<Integer> yearsSet = someObjectList.stream()
    .map(SomeObject::getYears)
    .collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.reverseOrder())));

推荐阅读