Consider the following code:
List fruits = Arrays.asList("apple", "banana", "cherry");
fruits.removeIf(s -> s.length() > 5);
What will be the contents of 'fruits' list after execution?
A["apple", "banana", "cherry"]
B["apple"]
C["apple", "cherry"]
D[]
Correct Answer:
B. ["apple"]
EXPLANATION
removeIf() removes all elements that satisfy the lambda predicate. Strings with length > 5 are "banana" (6 chars) and "cherry" (6 chars). Only "apple" (5 chars) remains as its length is not greater than 5.
A stream processes a list of strings and applies a lambda to convert them to uppercase. Which intermediate operation should be used?
Afilter(s -> s.toUpperCase())
Bmap(s -> s.toUpperCase())
Cpeek(s -> s.toUpperCase())
Dcollect(s -> s.toUpperCase())
Correct Answer:
B. map(s -> s.toUpperCase())
EXPLANATION
The map() intermediate operation transforms each element using the provided lambda function. filter() returns boolean, peek() doesn't transform, and collect() is a terminal operation. map() is the correct choice for transformation.
Which of the following lambda expressions is INVALID in Java?
A() -> System.out.println("Hello")
B(int x) -> x * x
C(x, y) -> { return x + y; }
D(x, y) -> return x + y;
Correct Answer:
D. (x, y) -> return x + y;
EXPLANATION
In a lambda expression, if the body uses curly braces, 'return' keyword is required. But without curly braces, 'return' keyword cannot be used. Option D is invalid because it has 'return' without curly braces.
Which of the following correctly uses a method reference as an alternative to a lambda expression?
ASystem.out::println instead of (x) -> System.out.println(x)
BString::length instead of (s) -> s.length()
CInteger::parseInt instead of (s) -> Integer.parseInt(s)
DAll of the above
Correct Answer:
D. All of the above
EXPLANATION
All three are valid method references that can replace their equivalent lambda expressions. Method references are a shorthand notation introduced in Java 8.
Consider the code: List names = Arrays.asList("Alice", "Bob"); names.forEach(name -> System.out.println(name)); What type of functional interface is used in forEach?
AFunction
BConsumer
CSupplier
DPredicate
Correct Answer:
B. Consumer
EXPLANATION
forEach accepts a Consumer functional interface. Consumer<T> takes an input and performs an action without returning anything, which matches the System.out.println action.