1

Is it possible to replace a series of if-else clauses such as the firstMatchedValue method below

foo() {
    String value = firstMatchedValue("input");
    // Do something useful.
}

String firstMatchedValue(String bar) {
    if (<condition1>) {
        return "value1";
    } else if (<condition2>) {
        return "value2";
    }
    return "value3";
}

with a lambda expression with structure similar to the following placeholder code?

foo() {
    String value = Optional.of("input")
        .someMethod(bar -> <condition1> return "value1")
        .someMethod(bar -> <condition2> return "value2")
        .orElse("value3")
}
stein
  • 58
  • 6
  • 4
    Have you ever heard of the ternary operator? It's not lambda, but it looks like what you are looking for. – Bar Hoshen Oct 11 '20 at 11:29
  • @BarHoshen I usually find that ternary operations get hard to read with more than 1 condition. Perhaps that is just an issue of me not using it enough. – stein Oct 11 '20 at 11:36
  • 5
    [Don't use `Optional`s for conditional logic](https://stackoverflow.com/questions/56235254/optional-vs-if-else-if-performance-java-8/56235329#56235329) – Lino Oct 11 '20 at 11:37
  • 3
    @stein It's likely more an issue with you not *formatting* the code adequately. – Andreas Oct 11 '20 at 12:08

0 Answers0