【发布时间】:2016-08-20 19:23:42
【问题描述】:
当数字是两个不同对象内部的属性时,我试图找出获取两个数字中最小的数字的最佳方法。每个对象(但不是两个)都可以为空,这可能导致空指针异常。每个对象都有自己的 getValue() 方法,该方法将返回一个 Long 值。有一些基本的 if/else 我不想做:
if (obj1 != null && obj2 != null) { // neither object is null
minValue = obj1.getValue() <= obj2.getValue() ? obj1.getValue() : obj2.getValue();
} else if (obj1 == null && obj2 != null) { // only obj1 is null
minValue = obj2.getValue();
} else { // only obj2 is null (they can't both be null, so we don't need an if for the situation where they're both null)
minValue = obj1.getValue();
}
我尝试了其他一些方法:
// can throw null pointer exception
Collections.min(Arrays.asList(obj1.getValue(), obj2.getValue()));
// while both objects have a getValue() method, they are of different types, so mapping doesn't work
Collections.min(Arrays.asList(obj1, obj2)
.filter(obj -> obj != null)
.map(obj -> obj.getValue()) // this line will fail since the methods correspond to different objects
.collect(Collectors.toList()));
我觉得这应该是一个相当简单的问题,但我的大脑不允许它工作。由于有一些 min 函数,您可以在对象可以为 null 的情况下进行双向处理?
【问题讨论】:
-
value的类型是什么? -
它们的类型是 Long
-
为什么不直接捕获 NullPointerException?
-
因为这很丑:/而且,这里先检查空值比捕获空指针更标准
-
mapToLong 可能比 map 更合适,但这仍然会遇到问题,即“getValue()”是一种针对 2 种不同类型对象的方法(它们不是同一个 pojo)