javaadvanced
Java Stream API
Stream, Lambda and functional interfaces
7 questions
By EZ4Code Team
1. What does the following code output? List<Integer> nums = List.of(1,2,3,4); int sum = nums.stream().filter(n -> n % 2 == 0).mapToInt(n -> n).sum(); System.out.println(sum);
List<Integer> nums = List.of(1,2,3,4);
int sum = nums.stream().filter(n -> n % 2 == 0).mapToInt(n -> n).sum();
System.out.println(sum);6
10
4
Error
Explanation: filter selects even numbers (2,4), mapToInt converts to IntStream, sum gives 6.
2. What is the difference between intermediate and terminal operations?
Intermediate operations are lazy; terminal operations trigger pipeline execution
Both execute immediately
Terminal operations return a Stream
Intermediate operations trigger execution
Explanation: Intermediate operations (such as map/filter) are lazy; the pipeline only executes when a terminal operation (such as collect/forEach/count) appears.
3. What is the common method to convert a Stream to a List?
.collect(Collectors.toList())
.toList() is always mutable
.asList()
.toArray()
Explanation: collect(Collectors.toList()) collects into a List; Java 16+ Stream.toList() returns an unmodifiable List.
4. What is a functional interface?
An interface with exactly one abstract method
An interface with no methods
An interface where all methods are default
An interface with multiple abstract methods
Explanation: A functional interface has exactly one abstract method (may include default/static methods), can be annotated with @FunctionalInterface, and can be directly assigned a lambda.
5. What does reduce do?
Reduces stream elements to a single value
Sorts elements
Groups elements
Removes duplicates
Explanation: reduce(binaryOperator) reduces a stream to a single value via an accumulator function, such as sum, product, or max.
6. What is the characteristic of parallelStream?
Uses ForkJoinPool for parallel processing, suitable for compute-intensive tasks without shared state
Always faster than stream
Executes sequentially
Cannot be used for large datasets
Explanation: parallelStream executes in parallel based on ForkJoinPool.commonPool(), suitable for compute-intensive tasks without shared state; may not be faster for small data or with order dependencies.
7. Which method is used for grouping?
Collectors.groupingBy()
Collectors.toList()
Stream.group()
Stream.partition()
Explanation: groupingBy(classifier) groups by a classifier function, returning Map<K, List<T>>; partitioningBy is a special case that partitions into two groups by a predicate.