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.