Is this the correct use of the functional interface?

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.

+7
java lambda java-8
source share
1 answer

No need to implement the Function interface. Instead, it is better to write a static method in some suitable class:

 public static <T, U> Function<T, U> ternary(Predicate<? super T> condition, Function<? super T, ? extends U> ifTrue, Function<? super T, ? extends U> ifFalse) { return t -> condition.test(t) ? ifTrue.apply(t) : ifFalse.apply(t); } 

And use like this:

 Function<String, Integer> safeStringLength = MyClass.ternary(condition, ifTrue, ifFalse); 

Also consider using import static for your utility class and simply write ternary(condition, ifTrue, ifFalse) .

This method is likely to be useful in some situations. Especially when you can use method references. For example:

 Stream.of(strings).map(ternary(String::isEmpty, x -> "none", String::trim))... 
+6
source share

All Articles