[英]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.