用方法引用'Objects :: nonNull'替换这个lambda [英] Replace this lambda with method reference 'Objects::nonNull'
问题描述
我编写了代码,用于从包含Date变量的对象列表中查找最新日期。
I have written code to find the latest date from a list of an object that contains Date variable.
list.stream()。map(segment - > segment.lastLoad).filter(x-> x!= null)。 max(Date :: compareTo).get()
但我收到声纳问题
用方法引用'Objects :: nonNull'替换这个lambda。
Replace this lambda with method reference 'Objects::nonNull'.
我是什么我无法弄清楚我在哪里可以使用声纳lint问题所述的方法参考。
What I am not able to figure out is where can I use Method reference stated by sonar lint issue.
推荐答案
.filter(x->x!=null) == .filter(Objects::nonNull)
有趣的是你已经使用了方法参考(但没看到这一个):
It's interesting that you already use a method reference in(but failed to see this one):
max(Date::compareTo)
此外,您显然会返回日期
但是来自可选<日期>
,您应该收到警告(如果使用IDEA),直接在可选$ c $上调用
获取
是不安全的c>。
Also you are obviously returning a Date
but from an Optional<Date>
, you should get a warning (if using IDEA) that it's not safe to call get
directly on an Optional
.
你还可以用 max(Date :: compareTo)
> max(Comparator.naturalOrder())因为日期
已经可比较
。
And you could also replace that max(Date::compareTo)
with max(Comparator.naturalOrder())
since Date
is already Comparable
.
这篇关于用方法引用'Objects :: nonNull'替换这个lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!