Govt. Exams
Entrance Exams
map() is an intermediate operation that returns an IntStream. The lambda expression (x -> x * 2) transforms each int, but map() itself returns IntStream, not the transformed value type.
List fruits = Arrays.asList("apple", "banana", "cherry");
fruits.removeIf(s -> s.length() > 5);
What will be the contents of 'fruits' list after execution?
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.
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.
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.
List numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream().filter(n -> n % 2 == 0).forEach(System.out::println);
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.
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.
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.
If a lambda body throws a checked exception, it must be declared in the functional interface's method signature. Otherwise, compilation will fail.
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.