In the following Java 8 code snippet, the intention is to iterate through a list of binary (2-arg) operators / lambda functions. Eclipse generates the error The method o(int,int) is undefined for the type X. The error is associated with the loop variable o. In case it is relevant, the version of Eclipse is "Eclipse Java EE IDE for Web Developers", Mars Release (4.5.0).
import java.util.List;
import java.util.function.BinaryOperator;
public class X {
public void f(List<BinaryOperator<Integer>> op) {
for (BinaryOperator<Integer> o : op) {
int x = o(1,2);
}
}
}
However, if the type of op is changed to List, there is no compiler error.
public void f(List<Integer> op) {
for (Integer o : op) {
int x = o;
}
}
Why does the for-loop work for List<Integer> but not for List<BinaryOperator<Integer>>, and how should lists of lambda functions be iterated in Java 8?
If you wish to apply the BinaryOperators of your List in a loop, you must invoke the apply method of that interface for each element of the List :
public void f(List<BinaryOperator<Integer>> op) {
for (BinaryOperator<Integer> o : op) {
int x = o.apply(1,2);
}
}
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