java - Is this a proper usage of Function interface? -
i trying familiar lambda functions. start decided write handy class called ternaryoperator
. so, question did ideology right or missing should done in different way?
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 usage of class this:
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 can calculate length of string if null oneliner.
so, if have ideas how write better ternaryoperator
or if think useless, please tell me.
no need implement function
interface. it's better write static method in appropriate class instead:
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 this:
function<string, integer> safestringlength = myclass.ternary(condition, iftrue, iffalse);
also consider using import static
utility class , write ternary(condition, iftrue, iffalse)
.
probably such method useful in situations. when can use method references. example:
stream.of(strings).map(ternary(string::isempty, x -> "none", string::trim))...
Comments
Post a Comment