I don't understand how to use lambdas to pass a method as a parameter.
Considering the following (not compiling) code, how can I complete it to get it work ?
public class DumbTest {
public class Stuff {
public String getA() {
return "a";
}
public String getB() {
return "b";
}
}
public String methodToPassA(Stuff stuff) {
return stuff.getA();
}
public String methodToPassB(Stuff stuff) {
return stuff.getB();
}
//MethodParameter is purely used to be comprehensive, nothing else...
public void operateListWith(List<Stuff> listStuff, MethodParameter method) {
for (Stuff stuff : listStuff) {
System.out.println(method(stuff));
}
}
public DumbTest() {
List<Stuff> listStuff = new ArrayList<>();
listStuff.add(new Stuff());
listStuff.add(new Stuff());
operateListWith(listStuff, methodToPassA);
operateListWith(listStuff, methodToPassB);
}
public static void main(String[] args) {
DumbTest l = new DumbTest();
}
}
Your
MethodParameter
should be some interface you define with a single method. This is referred to as a functional interface. You can then pass your methods in. A quick demonstration:You need to use method references.
You don't need to create a method like
operateListWith
, that's sort of the whole idea. Instead, you can operate on each value usingforEach
by doing something like this:For example:
Output:
In your case, you can get the value inside
Stuff
using.map
, and then operate on it usingforEach
, like this:The definition of
MethodParameter
is missing from your source code. To be used with lambda expressions, it must be a functional interface, for example:(The
@FunctionalInterface
annotation is optional.)To use the method, you have call the method from the interface:
And thirdly, a method reference always needs a context. In your case you have to do:
Declare your method to accept a parameter of an existing functional interface type which matches your method signature:
and call it as such:
As a further insight, you don't need the indirection of
methodToPassA
: