简体   繁体   中英

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. Each object has their own getValue() method, which will return a Long value. There's the basic if/else that I'd prefer not to do:

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?

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.

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

then do

Math.min(obj1, obj2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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