Returning another anonymous function in lambda expression java

Tom_G_99 :

Is it possible to return another function in a lambda expression in java? Say I have the following lambda expressions

addFive = (x) -> x+5;
addFiveIfPositive = (y) -> {
    if (y > 0) return addFive;
    else return y;
};

To give some context behind I'm asking this, I'm working with lambda expressions to define Comparators and for some comparators, I want to 'chain' comparators that I've already defined to not write the same code again, given some conditions like in the example above.

Any help would be appreciated.

Edit: This is a more representative example of what I'm working with.

import java.util.Comparator;

class Random{
    Integer val;
    String str;

    Random(int val, String str){
      this.val = new Integer(val);
      this.str = str;
    }
}

public class Temp{

  static Comparator<Random> c1 = (r1, r2) -> (r1.val).compareTo((r2.val));
  static Comparator<Random> c2 = (r1, r2) -> {
    if ((r1.str).compareTo((r2.str)) == 0){
      return c1.apply(r1,r2);
    }
    return (r1.str).compareTo((r2.str));
  };

  public static void main(String args){
    Random rand1 = new Random(1, "Hello");
    Random rand2 = new Random(2, "Hello");
    System.out.println(c2.compare(rand1, rand2));
  }
}

Using .apply() gives me the error

Temp.java:18: error: cannot find symbol
      return c1.apply(r1,r2);
               ^
  symbol:   method apply(Random,Random)
  location: variable c1 of type Comparator<Random>
Naman :

According to the edit, all you are looking for is to make use of:

Comparator<Random> c1 = Comparator.comparing(Random::getVal);
Comparator<Random> c2 = Comparator.comparing(Random::getStr).thenComparing(c1);;

that is because you already have Comparators supporting the use case of chaining with the thenComparing API. Do note that this is just a simplification of the following code:

Comparator<Random> c1 = (r1, r2) -> (r1.val).compareTo((r2.val));
Comparator<Random> c2 = (r1, r2) -> {
    if ((r1.str).compareTo((r2.str)) == 0){
        return c1.compare(r1,r2); //'compare' instead of 'apply'
    }
    return (r1.str).compareTo((r2.str));
};

Prior to the edit, you could have used a ternary operator to represent the condition such as:

IntFunction<Integer> addFive = x -> x + 5;
IntFunction<Integer> addFiveIfPositive = y -> y > 0 ? y + 5 : y;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=237784&siteId=1