0

i am new to java 8. i have list of string (List messagecodes) and string(code). i am trying to write java 8 functional way code for below logic.

if(messagecodes.contains(code)){
     callMethod1(message);
} else{ 
     callMethod2(message);
}

i created my own class like below

public class OptionalExt<T> {
    private final Optional<T> optional;
    private Predicate<T> test;

    public OptionalExt(final T optional) {
        this.optional = Optional.ofNullable(optional);
    }

    public static <T> OptionalExt<T> of(final T t) {
        return new OptionalExt<>(t);
    }

    public OptionalExt<T> condition(final Predicate<T> theTest) {
        this.test = theTest;
        return this;
    }

    public OptionalExt<T> when(final Consumer<T> consumer) {
        optional.filter(test).ifPresent(consumer);
        return this;
    }

    public void otherwise(final Consumer<T> consumer) {
        optional.filter(test.negate()).ifPresent(consumer);
    }
}

i am using the above class like this,

 OptionalExt
        .of(code)
        .condition((codee) -> codes.contains(codee))
        .when((code1) -> callMethod1(code1))
        .otherwise((code2) -> callMethod2(code2));

is there any other way to do the above logic in more functional way.

Jeffrey
  • 44,417
  • 8
  • 90
  • 141
  • You forgot to return `this` in `otherwise()` – Nir Alfasi May 05 '16 at 15:21
  • What's wrong with doing it declarative? If you want to do it the functional way you should try to make the API so it returns a value. Now it looks like your expecting side effects in the method calls. – ingara May 05 '16 at 15:44
  • If you wait until Java 9, there will be an [ifPresentOrElse](http://download.java.net/java/jdk9/docs/api/java/util/Optional.html#ifPresentOrElse-java.util.function.Consumer-java.lang.Runnable-) function. One thing you can learn from that one is that a `Runnable` would suffice for your `otherwise()` – Hank D May 05 '16 at 16:31
  • Your class doesn't qualify as a monad because there is no flatMap/map capability. There is no point keeping the predicate as a field -- you could apply any predicates to an Optional instance directly, passing it to the Optional's `.filter()` function. That way you can apply multiple predicates instead of just one. Consider making your type immutable--have your conditional filter return a new OptionalExt on each operation, for example. That way, you could do what you can do with Optional, "branch" multiple OptionalsExt instances from an existing OptionalExt. – Hank D May 05 '16 at 16:48

0 Answers0