用于在 Java 8 Stream 中排序的空安全日期比较器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36361156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:46:43  来源:igfitidea点击:

Null safe date comparator for sorting in Java 8 Stream

javajava-8java-stream

提问by Andrew

I'm using this to get the newest item. How can I get this to be null safe and sort with null dates last (oldest). createDt is a joda LocalDate object.

我正在使用它来获取最新的项目。我怎样才能让它成为空安全并用空日期最后(最旧)排序。createDt 是一个 joda LocalDate 对象。

Optional<Item> latestItem = items.stream()
                             .sorted((e1, e2) -> e2.getCreateDt().compareTo(e1.getCreateDt()))
                             .findFirst();

采纳答案by Paul Boddington

If it's the Items that may be null, use @rgettman's solution.

如果Items 可能为空,请使用@rgettman 的解决方案。

If it's the LocalDates that may be null, use this:

如果LocalDates 可能为空,请使用:

items.stream()
     .sorted(Comparator.comparing(Item::getCreateDt, Comparator.nullsLast(Comparator.reverseOrder())));

In either case, note that sorted().findFirst()is likely to be inefficient as most standard implementations sort the entire stream first. You should use Stream.mininstead.

在任何一种情况下,请注意这sorted().findFirst()可能是低效的,因为大多数标准实现首先对整个流进行排序。您应该改用Stream.min

回答by rgettman

You can turn your own null-unsafe Comparatorinto an null-safe one by wrapping it Comparator.nullsLast. (There is a Comparator.nullsFirstalso.)

您可以Comparator通过包装它来将您自己的 null-unsafe变成 null-safe Comparator.nullsLast。(还有一个Comparator.nullsFirst。)

Returns a null-friendly comparator that considers nullto be greater than non-null. When both are null, they are considered equal. If both are non-null, the specified Comparatoris used to determine the order.

返回一个认为null大于非空的对空友好的比较器。当两者都是 时null,它们被认为是相等的。如果两者都不为空,Comparator则使用指定的来确定顺序。

.sorted(Comparator.nullsLast(
     (e1, e2) -> e2.getCreateDt().compareTo(e1.getCreateDt())))
.findFirst();

回答by Mohsen Kashi

write your custom one:

写你的自定义:

stream().sorted((o1, o2) ->
                        (o1.getF1() == null || o2.getF1() == null) ? 1 :
                                o1.getF1().compareTo(o2.getF1())
                )

This is nulls first sorting, change the return value of if statement from 1 to -1 for nulls last

这是空值优先排序,最后将if语句的返回值从1改为-1