Java 8's orElse not working as expected

Consider the following method which returns a field if it exists or recursively calls itself until the field is found:

private Field getField(Class<?> clazz, String p) {
    Optional<Field> field = Arrays.stream(clazz.getDeclaredFields())
            .filter(f -> p.equals(f.getName()))
            .findFirst();

    return field.isPresent() ? field.get() : getField(clazz.getSuperclass(), p);
}

While this works, I thought I could shorten it to:

private Field getField(Class<?> clazz, String p) {
    return Arrays.stream(clazz.getDeclaredFields())
            .filter(f -> p.equals(f.getName()))
            .findFirst()
            .orElse(getField(clazz.getSuperclass(), p));
}

But the strange thing is that the .orElse part seems to always be called.

What am I missing here?

Answers


The arguments for a method are always evaluated before the method is called. You want orElseGet which takes a Supplier that will only be invoked if the Optional is not present:

private Field getField(Class<?> clazz, String p) {
    return Arrays.stream(clazz.getDeclaredFields())
            .filter(f -> p.equals(f.getName()))
            .findFirst()
            .orElseGet(() -> getField(clazz.getSuperclass(), p));
}

Need Your Help

Embedded HTML in link_to body in Rails

ruby-on-rails link-to

What is the best way to go about getting embedded HTML in the body of a link generated with the link_to method?

How to save a png from javascript variable

javascript image save

I have an image encoded in base64 in a javascript variable : data:image/png;base64, base64 data