Java 8, how to compose (Bi)Function from (Bi)Predicate -
i don't believe question specific bi
versions of these java 8 classes, hence parens in question title.
i composed function create apache commons lang3 pair
object following requirements:
- if both left , right null, pair should null
- if left , right equal 1 another, pair should null
- otherwise, pair should created, either side of may null
i did within method follows:
bipredicate<string,string> valuesexist = (pre, post) -> pre != null || post != null; final bipredicate<string, string> valuesdiffer = valuesexist.and((pre, post) -> (pre != null) ? ! pre.equals(post) : true); bifunction<string, string, pair<string,string>> createpair = (pre, post) -> (valuesdiffer.test(pre, post)) ? immutablepair.of(pre, post) : null; // usage looks like: pair<string, string> mypair = createpair.apply(myvalue1, myvalue2)
i had 3 questions:
- is there way avoid 2 bipredicates? second 1 needed because referencing inside bifunction requires
final
- is there way move out of method , surrounding class?
- is there obvious "clean-up" missed?
update
based upon 1 of answers below, solution without java-8 features seems practical:
static boolean filterpairargs(string pre, string post) { return (pre != null || post != null) && ((pre == null) || !pre.equals(post)); } static pair<string, string> createpair(string v1, string v2) { if (filterpairargs(v1, v2)) { return new pair<>(v1, v2); } return null; } // usage looks like: pair<string, string> mypair = createpair(myvalue1, myvalue2);
the null-safe handling of objects.equals() method clean things here.
personally, i'd put in helper function. can use functionally tidy method reference or call method.
static pair<string, string> topair(string pre, string post) { return objects.equals(pre, post) ? null : immutablepair.of(pre, post); }
wiki
Comments
Post a Comment