What will be the output of the following code?
List numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream().filter(n -> n % 2 == 0).forEach(System.out::println);
A1 3 5
B2 4
C1 2 3 4 5
DCompilation error
Correct Answer:
B. 2 4
EXPLANATION
The filter operation with lambda expression (n -> n % 2 == 0) filters even numbers only. So 2 and 4 are printed, each on a new line due to println.
Which functional interface is used to create a lambda expression that takes two integers and returns a boolean value?
ABiPredicate
BBiFunction
CBiConsumer
DSupplier
Correct Answer:
A. BiPredicate
EXPLANATION
BiPredicate<T, U> is a functional interface that takes two parameters and returns a boolean. This matches the requirement of taking two integers and returning a boolean value.
In a lambda expression, what does the arrow (->) operator represent?
AAssignment operator
BSeparation between parameters and body
CComparison operator
DLogical AND operator
Correct Answer:
B. Separation between parameters and body
EXPLANATION
The arrow (->) in lambda expressions separates the parameter list on the left from the method body on the right. It's a syntax element specific to lambda expressions.
What is the purpose of a Predicate functional interface in Java?
ATo transform one type of object to another
BTo perform an action without returning a value
CTo test a condition and return a boolean value
DTo supply a value without taking any input
Correct Answer:
C. To test a condition and return a boolean value
EXPLANATION
Predicate<T> is a functional interface that takes a single input of type T and returns a boolean. It's commonly used for filtering operations in streams.
Which annotation is used to mark an interface as a functional interface in Java?
A@Function
B@FunctionalInterface
C@Lambda
D@Interface
Correct Answer:
B. @FunctionalInterface
EXPLANATION
@FunctionalInterface is the standard annotation introduced in Java 8 to explicitly mark an interface as a functional interface. It helps in compile-time checking.
Which of the following is a valid functional interface that can be used with lambda expressions?
AAn interface with exactly one abstract method
BAn interface with multiple abstract methods
CAn interface with no abstract methods
DAn interface with static methods only
Correct Answer:
A. An interface with exactly one abstract method
EXPLANATION
A functional interface must have exactly one abstract method. This is the defining characteristic that allows it to be used with lambda expressions and method references.