Which functional interface, when entered into the blank below, allows the class to compile?
package mypkg;//from www .j a va 2s. com import java.util.*; import java.util.function.*; public class Main { private static void m(List<Double> prices, scanner) { prices.forEach(scanner); } public static void main(String[] right) { List<Double> prices = Arrays.asList(1.2, 6.5, 3.0); m(prices, p -> { String result = p<5 ? "Correct" : "Too high"; System.out.println(result); }); } }
D.
The forEach()
method requires a Consumer instance.
Option C can be immediately discarded because Supplier<Double> does not inherit Consumer.
Option B is also incorrect.
DoubleConsumer does not inherit from Consumer.
In this manner, primitive functional interfaces cannot be used in the forEach()
method.
Option A seems correct, since forEach()
does take a Consumer instance, but it is missing a generic argument.
Without the generic argument, the lambda expression does not compile because the expression p<5 cannot be applied to an Object.
The correct functional interface is Consumer<Double>, and since that is not available, Option D is the correct answer.