Skip to content
Advertisement

Java 8 reduce method calls depending on a value

How to optimize method that returns the first non empty value returned of the checkN() methods and prevent the rest method calls and isEmpty() calls:

JavaScript

#1 I thought of using stream filter and return first that has value, but it requires to call each check:

JavaScript

SOLVED

as M A suggested, finalized solution for me was:

JavaScript

Advertisement

Answer

Instead of constructing a Stream of Strings, you can do a Stream of Supplier<String>, which would defer the invocation of the method until the filter needs to be checked in the stream pipeline:

JavaScript

A better variant is to do the mapping from Supplier to the result String before the filter (the advantage is that this won’t call the method with the non-empty result twice):

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement