I have a class which has several methods returning the same type. So, for example, I have the following object definition:
interface MyClass {
String first();
String second();
}
Then I have a method, which accepts a list of objects of this class, and should call either first() or second() method depending on the parameter. An example:
void myMethod(List<MyClass> objs, boolean executeFirst) {
objs.forEach(obj -> System.out.println(executeFirst ? obj.first() : obj.second()));
}
Is there any way of replacing the executeFirst parameter with a reference to and instance method, which I want to execute on the objs object? So, for example, ideally I'd like to have something like this:
void myMethod(List<MyClass> objs, Supplier<String> instanceMethod) {
objs.forEach(obj -> System.out.println(obj::instanceMethod.get());
}
You need a Function<MyClass, String>, not a Supplier:
public void foo() {
myMethod(someList, MyClass::first);
}
void myMethod(List<MyClass> objs, Function<MyClass, String> instanceMethod) {
objs.forEach(obj -> System.out.println(instanceMethod.apply(obj));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With