lambda expression vs static method

Viewed 9443

I had a question about reusability of lambda expression without code duplication. For example if I have a helper method I can easily code it as a static method and can refer to it from other classes without code duplication. How would this work in lambda expression ? Example: I have the following static method written

public class MyUtil {

    public static int doubleMe(int x) {
        return x * 2;
    }
}

I can reuse the same method without code duplication in multiple places across the project

public class A {

    public void someOtherCalculation() {
        MyUtil.doubleMe(5);
    }
}

public class B {

    public void myCalculation() {
        MyUtil.doubleMe(3);
    }
}

How would it work when it comes to a lambda function, write the function once and use the same at multiple class.

Function<Integer, Integer> doubleFunction = x -> x * 2;

In my example, where would I write the above lambda function and how would I reuse the same in class A and B ?

5 Answers

You can do something like below.

class Fn {
  public static final Function<Integer, Integer> X2TIMES = x -> x *2;
}

class Test {
  public static void main (String[] args) {
    System.out.println(Fn.X2TIMES.apply(5));
  }
}
Related