【问题标题】:Ignore zero values at sorted in lambda忽略在 lambda 中排序的零值
【发布时间】:2020-07-09 21:21:34
【问题描述】:

如果值是0 0 4 2 1 7,我在对值进行排序时尝试忽略零值,它应该首先是1 2 4 7 0 0

List<PersonItem> collect = personLists.stream()
.sorted((p1,p2) -> 
    (p1.getCelebrityWeighting() == null ? 0 : p1.getCelebrityWeighting()) 
     - (p2.getCelebrityWeighting() == null ? 0 : p2.getCelebrityWeighting()))
.collect(Collectors.toList());

【问题讨论】:

  • 如果您有null 值,最好使用Comparator.nullsLast 进行比较,而不是将它们映射到0 作为值。
  • 您想在排序列表的末尾看到 0/null 值,不是吗?这个比较器对你有用吗? .sorted((p1,p2) -> { if (p1 == null || p1.w() == 0) return 1; // if (p2 == null || p2.w() == 0) return -1; // return p1.w() - p2.w(); }) 假设 pw() 是 p.getCelebrityWeighting()
  • 这个问题不清楚。请先为您的问题添加更多详细信息。这也可能有帮助:stackoverflow.com/help/minimal-reproducible-example

标签: java spring lambda java-8 comparator


【解决方案1】:

null 值排在最后

请注意,0 值将是第一个。这是null 友好的。

personLists.sort(
    Comparator.comparing(
        PersonItem::getCelebrityWeighting,                 // key extractor, comparing by...
        Comparator.nullsLast(Comparator.naturalOrder()))); // natural order, nulls last

0、0、1、2、4、7、空、空


0 值排在最后

请注意,此解决方案对 null 不友好,getCelebrityWeighting() 不得为 null,并且在所有 null 值都替换为 0 时有效。返回 1or-1` 时请注意比较器中的顺序。

personLists.sort((first, second) -> {
    if (first.getCelebrityWeighting() == 0) return 1;                       // 0 last
    if (second.getCelebrityWeighting() == 0) return -1;                     // 0 last
    return first.getCelebrityWeighting() - second.getCelebrityWeighting();  // standard
});

1、2、4、7、0、0、0、0


0null 值排在最后

以上示例的组合是nullfriendly:

personLists.sort(
    Comparator.comparing(
        PersonItem::getCelebrityWeighting,         // key extractor, comparing by...
        Comparator.nullsLast((first, second) -> {  // here you have weightings
             if (first == 0) return 1;             // 0 and then null last
             if (second == 0) return -1;
             return first - second;
        })));

1、2、4、7、0、0、空、空

【讨论】:

  • 当两个参数都为零时,比较器必须返回零。
猜你喜欢
  • 2020-12-10
  • 2023-03-26
  • 2020-05-19
  • 1970-01-01
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
  • 2014-04-23
  • 2019-06-09
相关资源
最近更新 更多