I am trying to get familiar with lambda functions. For starters, I decided to write a convenient class called TernaryOperator . So the question is, did I get the ideology right, or am I missing something because it has to be done differently?
public class TernaryOperator<T, U> implements Function<T, U> { private final Function<T, U> f; public TernaryOperator(Predicate<? super T> condition, Function<? super T, ? extends U> ifTrue, Function<? super T, ? extends U> ifFalse) { this.f = t -> condition.test(t) ? ifTrue.apply(t) : ifFalse.apply(t); } @Override public U apply(T t) { return f.apply(t); } }
I see the use of this class as follows:
Predicate<Object> condition = Objects::isNull; Function<Object, Integer> ifTrue = obj -> 0; Function<CharSequence, Integer> ifFalse = CharSequence::length; Function<String, Integer> safeStringLength = new TernaryOperator<>(condition, ifTrue, ifFalse);
And now I can calculate the length of any string, even if it is null with this oneliner.
So, if you have ideas on how to write TernaryOperator better, or if you think this is useless, tell me.
java lambda java-8
antonpp
source share