[英]java find the smallest of two numbers coming from two different object types when one can be null
当数字是两个不同对象中的属性时,我试图找出抓住两个数字中最小的最佳方法。 每个(但不是两个)对象都可以为null,这可能导致null指针异常。 每个对象都有自己的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的情况?
long minValue = Math.min(obj1 == null ? Long.MAX_VALUE : obj1.getValue(),
obj2 == null ? Long.MAX_VALUE : obj2.getValue());
我不确定我是否完全理解您的问题,但是如果我这样做,则可以执行以下操作:
if(obj1 == null)
minValue = obj2.getValue();
else if(obj2 == null)
minValue = obj1.getValue();
else minValue = obj1.getValue() < obj2.getValue() ? obj1.getValue() : obj2.getValue();
您可能有一个接受ObjType的方法,进行空检查并返回Long.MAX_VALUE,如果该值为空,则返回该值。
public Long getVal(ObjType val)
{
if(val != null)
{
return val.getValue();
}
return Long.MAX_VALUE;
}
然后做
Math.min(obj1, obj2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.