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:

  1. if both left , right null, pair should null
  2. if left , right equal 1 another, pair should null
  3. 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:

  1. is there way avoid 2 bipredicates? second 1 needed because referencing inside bifunction requires final
  2. is there way move out of method , surrounding class?
  3. 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

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -