简体   繁体   English

当一个可以为null时,java查找来自两种不同对象类型的两个数字中的最小值

[英]java find the smallest of two numbers coming from two different object types when one can be null

I'm trying to figure out the best way of grabbing the smallest of two numbers when the numbers are attributes inside of two different objects. 当数字是两个不同对象中的属性时,我试图找出抓住两个数字中最小的最佳方法。 Each, but not both, of the objects can be null, which can lead to null pointer exceptions. 每个(但不是两个)对象都可以为null,这可能导致null指针异常。 Each object has their own getValue() method, which will return a Long value. 每个对象都有自己的getValue()方法,该方法将返回Long值。 There's the basic if/else that I'd prefer not to do: 我不喜欢基本的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();
}

I've tried some other things: 我尝试了其他一些方法:

// 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()));

I feel like this should be a fairly easy problem, but my brain's not allowing it to work. 我觉得这应该是一个相当容易的问题,但是我的大脑不允许它工作。 There's due to be some min function where you can bipass a situation where the object can be null? 由于存在一些min函数,您可以在其中传递对象可以为null的情况?

long minValue = Math.min(obj1 == null ? Long.MAX_VALUE : obj1.getValue(),
                         obj2 == null ? Long.MAX_VALUE : obj2.getValue());

I am not sure I fully understand your question, but if I do, something like this could work: 我不确定我是否完全理解您的问题,但是如果我这样做,则可以执行以下操作:

if(obj1 == null) 
   minValue = obj2.getValue();
else if(obj2 == null)
   minValue = obj1.getValue();
else minValue = obj1.getValue() < obj2.getValue() ? obj1.getValue() : obj2.getValue();

You could have a method that takes in your ObjType, does a null check and returns Long.MAX_VALUE, or the value if it's null. 您可能有一个接受ObjType的方法,进行空检查并返回Long.MAX_VALUE,如果该值为空,则返回该值。

public Long getVal(ObjType val)
{
    if(val != null)
    {
       return val.getValue();
    }
    return Long.MAX_VALUE;
}

then do 然后做

Math.min(obj1, obj2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM