Choosing non null attributes

Viewed 483

I have an object with 3 attributes, where only one can be not null. I would like to call a methode with the argument that is not null but if possible without a large if else statement.

I thought of something like this, but it doesn't work.

myMethode(myObj.getAttr1() || myObj.getAttr2() || myObj.getAttr3());

What would be a good solution?

3 Answers

One option is to stream the attributes and filter the first (presumably, only) non-null one:

myMethod(Stream.of(myObj.getAttr1(), myObj.getAttr2(), myObj.getAttr3())
               .filter(Objects::notNull)
               .findFirst()
               .orElse(null) // Or perhaps throw an exception?
        );

|| is a logical or operator and can be used only between two boolean types, which is why your code doesn't work.

myMethode(myObj.getAttr1() != null ? myObj.getAttr1() : 
          myObj.getAttr2() != null ? myObj.getAttr2() : 
          myObj.getAttr3() != null ? myObj.getAttr3() : null);

if your object only 3 attributes , you can use reflection like below

final long notNullAttributeCount = Arrays.stream(myObj.getClass().getFields())
        .map(f -> {
            try {
                f.setAccessible(true);
                return f.get(myObj);
            } catch (IllegalAccessException e) {
                return null;
            }
        }).filter(Objects::nonNull).count();

if (notNullAttributeCount == 1) {
    //do your staff
}
Related