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.
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.
Correct Answer:
A. Optional.of(value).map(x -> x.toUpperCase()).orElse("default")
EXPLANATION
Optional with map() using a lambda expression is the functional programming approach. It's safe, readable, and chains operations effectively. Options B, C, and D are imperative approaches.
What is the difference between a lambda expression and an anonymous inner class in Java?
ALambda expressions are only for functional interfaces, while anonymous classes can implement any interface
BLambda expressions are cleaner and more concise for functional interfaces
CLambda expressions create new scope, while anonymous classes don't
DBoth A and B
Correct Answer:
D. Both A and B
EXPLANATION
Lambda expressions can only be used with functional interfaces (single abstract method), whereas anonymous classes can implement any interface. Lambda expressions are also more concise.
Both expressions correctly sort by length. Option B uses Integer.compare (safer for int overflow), while Option C uses direct subtraction. Both work correctly here.