Courseiva

CCNA Working with Streams and Lambda Expressions Questions

14 of 89 questions · Page 2/2 · Working with Streams and Lambda Expressions · Answers revealed

76
MCQhard

A developer needs to process a stream of integers and collect the results into a Map<Integer, List<Integer>> where keys are the integers themselves and values are lists containing the number and its square. Which collector should be used?

A.Collectors.toMap(Function.identity(), i -> Arrays.asList(i, i * i), (v1, v2) -> v1)
B.Collectors.groupingBy(Function.identity(), Collectors.mapping(i -> i * i, Collectors.toList()))
C.Collectors.toMap(Function.identity(), i -> Arrays.asList(i, i * i), (v1, v2) -> v1, HashMap::new)
D.Collectors.toMap(Function.identity(), i -> i * i)
AnswerC

Correctly creates map with list values, handles duplicates by keeping first.

Why this answer

It uses the four-argument overload of `Collectors.toMap()`: a key mapper (`Function.identity()`), a value mapper (a lambda that creates a `List<Integer>` containing the number and its square), a merge function (`(v1, v2) -> v1`) to handle duplicate keys (which won't occur here since keys are unique integers), and a `HashMap::new` supplier to ensure the map type is explicitly `HashMap`. This satisfies the requirement of producing a `Map<Integer, List<Integer>>` where each key maps to a list of the number and its square.

Exam trap

Oracle often tests the distinction between the three-argument and four-argument `toMap()` overloads, trapping candidates who omit the map supplier or who confuse `groupingBy()` with `toMap()` when the requirement is to store both the original element and a derived value in the map value.

How to eliminate wrong answers

Option A is wrong because `Collectors.toMap(Function.identity(), i -> Arrays.asList(i, i * i), (v1, v2) -> v1)` lacks a map supplier, so it returns a default `HashMap` but will throw `IllegalStateException` at runtime if duplicate keys are encountered (the merge function is only used for merging, not for preventing the exception when keys are truly duplicate; however, here keys are unique so it would work, but the question expects the four-argument version to guarantee the correct map type and avoid ambiguity). Option B is wrong because `Collectors.groupingBy(Function.identity(), Collectors.mapping(i -> i * i, Collectors.toList()))` produces a `Map<Integer, List<Integer>>` where each value is a list of squares only, not a list containing both the number and its square. Option D is wrong because `Collectors.toMap(Function.identity(), i -> i * i)` produces a `Map<Integer, Integer>` with only the square as the value, not a `List<Integer>`.

77
MCQhard

A developer writes the following code to print a list of strings in order: list.stream().map(s -> s.toUpperCase()).forEach(System.out::print). They want to parallelize the processing but must preserve the output order. Which change is correct and most appropriate?

A.list.parallelStream().map(s -> s.toUpperCase()).forEach(System.out::print);
B.list.parallelStream().map(s -> s.toUpperCase()).forEachOrdered(System.out::print);
C.list.stream().parallel().map(s -> { synchronized(System.out) { return s.toUpperCase(); } }).forEach(System.out::print);
D.list.stream().parallel().map(s -> s.toUpperCase()).sequential().forEach(System.out::print);
AnswerB

forEachOrdered ensures that processing respects the encounter order, even in a parallel stream.

Why this answer

`forEachOrdered` guarantees that elements are processed in encounter order even when the stream is parallelized. The `map` operation is stateless and can run in parallel, but the terminal operation must preserve order, which `forEachOrdered` does by enforcing sequential output in the stream's encounter order.

Exam trap

The trap here is that candidates often confuse `forEach` with `forEachOrdered`, assuming that `forEach` in a parallel stream still preserves order, or they incorrectly think synchronization in `map` can fix ordering issues.

How to eliminate wrong answers

Option A is wrong because `forEach` does not guarantee encounter order in a parallel stream; it may print elements out of order. Option C is wrong because synchronizing on `System.out` inside `map` is unnecessary and inefficient; it does not fix the ordering issue because `forEach` still does not preserve order. Option D is wrong because calling `sequential()` after `parallel()` makes the stream sequential again, defeating the purpose of parallelization.

78
MCQeasy

A developer wants to compute the product of all even numbers in a stream of integers. Which of the following correctly implements this using streams?

A.reduce(1, (a, b) -> (a % 2 == 0) ? a * b : a)
B.filter(n -> n % 2 == 0).reduce(0, (a, b) -> a * b)
C.reduce(1, (a, b) -> a * b)
D.filter(n -> n % 2 == 0).reduce(1, (a, b) -> a * b)
AnswerD

Correct. Filter ensures only even numbers are processed, then reduction multiplies them using identity 1.

Why this answer

It first filters the stream to keep only even numbers (n % 2 == 0), then uses reduce with an identity of 1 and a multiplication lambda (a, b) -> a * b. The identity 1 is the neutral element for multiplication, ensuring that if no even numbers exist, the result is 1 rather than an error or incorrect value.

Exam trap

The trap here is that candidates often forget the identity value must be the neutral element for the reduction operation, so they pick Option B with identity 0 for multiplication, or they skip filtering entirely and pick Option C, thinking the product of all numbers is sufficient.

How to eliminate wrong answers

Option A is wrong because it uses reduce without filtering, so it multiplies all numbers together and only conditionally includes the current element based on the accumulator's parity, which is incorrect logic and can produce wrong results (e.g., for stream [2, 3], it would compute 1*2=2, then check if 2%2==0 -> true, so 2*3=6, but 3 is odd). Option B is wrong because it uses reduce with identity 0, which makes the product always 0 (since 0 multiplied by any number is 0). Option C is wrong because it multiplies all numbers in the stream without filtering for even numbers, computing the product of all integers instead of just evens.

79
MCQhard

Refer to the exhibit. A developer runs the code and gets an IllegalStateException on the second forEach. Which statement explains why?

A.The filter operation is not lazy.
B.The map operation modifies the source list.
C.The stream is not closed after the first terminal operation.
D.The stream has already been operated upon or closed.
AnswerD

Correct. A stream cannot be reused after a terminal operation.

Why this answer

A Stream in Java cannot be reused after a terminal operation has been executed. Once the first forEach terminal operation completes, the stream is consumed and closed. Attempting to call another terminal operation (the second forEach) on the same stream reference throws an IllegalStateException with the message 'stream has already been operated upon or closed'.

Exam trap

A common misconception in OCP Java exam questions is that streams can be reused like collections, or that the exception is due to resource leaks or modification of the source.

How to eliminate wrong answers

Option A is wrong because the filter operation is indeed lazy (intermediate operations are lazy in Java streams), but laziness does not cause an IllegalStateException on a subsequent terminal operation. Option B is wrong because the map operation does not modify the source list; map returns a new stream with transformed elements and does not alter the original list. Option C is wrong because streams do not need to be explicitly closed after a terminal operation; they are automatically consumed and cannot be reused, but the exception is not about resource closure but about stream reuse.

80
Multi-Selecthard

Which THREE of the following are true about the Optional class? (Choose three.)

Select 3 answers
A.Optional.empty().orElseThrow(IllegalStateException::new) throws IllegalStateException
B.Optional.of(null) returns an empty Optional
C.Optional.ofNullable(null) returns an empty Optional
D.Optional.get() on empty Optional returns null
E.Optional.ifPresent(v -> System.out.println(v)) with empty Optional does nothing
AnswersA, C, E

orElseThrow with a Supplier will throw the exception if the Optional is empty.

Why this answer

`Optional.empty().orElseThrow(IllegalStateException::new)` explicitly throws a new `IllegalStateException` when the Optional is empty. The `orElseThrow` method is designed to throw the provided exception supplier's exception if no value is present.

Exam trap

Oracle OCP Java 17 often tests the distinction between `Optional.of()` and `Optional.ofNullable()`, and the fact that `Optional.get()` throws `NoSuchElementException` rather than returning null, to catch candidates who confuse Optional with a simple null wrapper.

81
MCQmedium

A team needs to process a large collection of orders to calculate total revenue per region. They decide to use parallel streams to improve performance. Which statement about using parallel streams for this task is true?

A.The stream() method returns a parallel stream by default.
B.Using a parallel stream with a stateful lambda operation can lead to incorrect results.
C.Parallel streams always provide better performance than sequential streams.
D.Parallel streams cannot be used with custom thread pools.
AnswerB

Stateful lambdas (e.g., accumulating into a non-thread-safe collection) cause race conditions in parallel pipelines.

Why this answer

Parallel streams split the workload across multiple threads, and if the lambda operation is stateful (e.g., modifying a shared variable like a counter or a non-thread-safe collection), it can cause race conditions and produce incorrect results. The Streams API documentation explicitly warns against using stateful lambdas with parallel streams to avoid data integrity issues.

Exam trap

The trap here is that candidates may assume parallel streams are always faster (Option C) or that they cannot use custom thread pools (Option D), but the core exam focus is on the requirement for stateless, non-interfering lambdas to ensure correctness in parallel processing.

How to eliminate wrong answers

Option A is wrong because the stream() method returns a sequential stream, not a parallel stream; to obtain a parallel stream, you must call parallelStream() or convert a sequential stream with .parallel(). Option C is wrong because parallel streams do not always provide better performance; they incur overhead for thread management and partitioning, and may be slower than sequential streams for small datasets or operations with high contention. Option D is wrong because parallel streams can use custom thread pools by submitting the parallel stream operation to a custom ForkJoinPool, for example via ForkJoinPool.commonPool() or by wrapping the operation in a custom pool's submit() call.

82
MCQmedium

A developer uses a stateful lambda in a parallel stream. Which of the following is a potential consequence?

A.Non-deterministic results
B.ConcurrentModificationException
C.All of the above
D.Improved performance
AnswerA

Correct. Stateful lambdas in parallel streams can cause race conditions, leading to non-deterministic outcomes.

Why this answer

Stateful lambdas (e.g., those that modify shared mutable state) in parallel streams break the non-interference and statelessness requirements of the Stream API. Because parallel streams split the source into substreams processed by multiple threads, the lack of synchronization leads to race conditions, producing non-deterministic results that vary between runs.

Exam trap

The trap here is that candidates confuse stateful lambdas with structural modification of the source, incorrectly assuming ConcurrentModificationException is the primary risk, when in fact the core issue is non-determinism from unsynchronized shared state in parallel streams.

How to eliminate wrong answers

Option B is wrong because ConcurrentModificationException occurs when a stream pipeline structurally modifies the stream source (e.g., adding to a collection while iterating), not from using a stateful lambda that merely reads and writes shared mutable state. Option C is wrong because not all consequences listed apply; only non-deterministic results are a direct consequence, while ConcurrentModificationException is unrelated and improved performance is false. Option D is wrong because stateful lambdas in parallel streams typically degrade performance due to synchronization overhead or contention, and they never improve performance over stateless lambdas.

83
MCQeasy

You are developing an online bookstore application. You have a list of Book objects, each with fields: String title, double price, and String genre. You need to generate a report that lists the total price of books in each genre, but only for genres where the average price is greater than $20.00. You are using Java 17 and streams. Which approach correctly accomplishes this task?

A.books.stream() .collect(Collectors.groupingBy(Book::getGenre, Collectors.mapping(Book::getPrice, Collectors.toList()))) .entrySet().stream() .filter(e -> e.getValue().stream().mapToDouble(Double::doubleValue).average().orElse(0) > 20) .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream().mapToDouble(Double::doubleValue).sum()));
B.books.stream() .filter(b -> b.getPrice() > 20) .collect(Collectors.groupingBy(Book::getGenre, Collectors.summingDouble(Book::getPrice)));
C.books.stream() .collect(Collectors.groupingBy(Book::getGenre, Collectors.averagingDouble(Book::getPrice))) .entrySet().stream() .filter(e -> e.getValue() > 20) .collect(Collectors.toMap(Map.Entry::getKey, e -> { return books.stream().filter(b -> b.getGenre().equals(e.getKey())).mapToDouble(Book::getPrice).sum(); }));
D.books.stream() .collect(Collectors.groupingBy(Book::getGenre, Collectors.summingDouble(Book::getPrice))) .entrySet().stream() .filter(e -> e.getValue() > 20) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
AnswerA

Correct. It first groups books by genre, collecting prices into a list. Then it filters entries where the average price exceeds $20 using mapToDouble and average(), and finally sums the prices for those genres. This two-step process correctly computes the average per genre before filtering, then sums the total per genre.

Why this answer

It first groups books by genre, collecting prices into lists, then filters entries where the average price exceeds $20 using `mapToDouble` and `average()`, and finally sums the prices for those genres. This two-step process correctly computes the average per genre before filtering, then sums the total per genre.

Exam trap

Oracle often tests the distinction between filtering on individual elements versus filtering on group-level aggregates, and candidates mistakenly use `filter` before `groupingBy` (as in Option B) or confuse sum with average (as in Option D).

How to eliminate wrong answers

Option B is wrong because it filters individual books with price > 20 before grouping, which excludes books with price ≤ 20 from the genre totals, but the requirement is to filter genres based on average price > 20, not individual book prices. Option C is wrong because it recalculates the sum by re-streaming the original list inside the collector, which is inefficient and breaks the stream pipeline's declarative nature, though it would produce the correct result; however, it violates the single-pass stream principle and is not the idiomatic approach. Option D is wrong because it filters genres where the total sum is > 20, not the average, which is a different condition and would include genres with many cheap books whose total sum exceeds 20 but average is below 20.

84
MCQmedium

A financial application processes millions of transactions daily. The original code uses a for loop to aggregate transactions into a Map<Long, TransactionSummary> where the key is account ID. To improve performance, a developer refactors it using parallel streams: transactions.parallelStream() .collect(Collectors.toMap( Transaction::getAccountId, Function.identity(), (t1, t2) -> t1.merge(t2), // merging logic HashMap::new )); After deployment, they observe that the resulting map is smaller than expected and some transaction summaries are missing. Profiling shows the merge function is called infrequently, suggesting that the map is losing entries. What is the most likely cause and the correct fix?

A.Remove parallelStream() and use sequential stream to avoid concurrency issues.
B.The merge function is not associative; change it to use a combiner that is associative.
C.Use forEach with a ConcurrentHashMap and putIfAbsent to manually merge.
D.Replace HashMap::new with ConcurrentHashMap::new in the collector.
AnswerD

In parallel streams, the default toMap collector uses HashMap which is not thread-safe. ConcurrentHashMap allows safe concurrent insertion and merging.

Why this answer

The issue is that `HashMap::new` is not thread-safe. When `parallelStream()` splits the stream into multiple threads, each thread creates its own `HashMap` for partial results. These partial maps are then merged using the collector's combiner, but `HashMap` does not guarantee thread safety during concurrent access or merging.

Using `ConcurrentHashMap::new` ensures that the map can be safely populated and combined across threads, preventing lost entries. The merge function itself is associative (merging two summaries into one), so the problem is purely the thread-unsafe map supplier.

Exam trap

Oracle often tests the misconception that the merge function must be associative when the real culprit is the thread-unsafe map supplier in parallel stream collectors.

How to eliminate wrong answers

Option A is wrong because removing parallelism is unnecessary; the core issue is the thread-unsafe map supplier, not parallelism itself. Option B is wrong because the merge function `(t1, t2) -> t1.merge(t2)` is associative (merging is order-independent) and not the cause of missing entries. Option C is wrong because using `forEach` with `ConcurrentHashMap` and `putIfAbsent` would work but is a manual, less idiomatic approach; the correct fix is to simply supply a thread-safe map to the collector, which is simpler and preserves the parallel stream's performance benefits.

85
MCQmedium

A developer adds .peek(System.out::println) to a stream pipeline to debug, but no output is printed. What is the most likely reason?

A.The stream is parallel
B.The pipeline lacks a terminal operation
C.The peek operation is placed after the terminal operation
D.The stream is empty
AnswerB

Correct. Without a terminal operation, the pipeline never executes, so peek never runs.

Why this answer

Stream pipelines are lazy; intermediate operations like peek() are only executed when a terminal operation (e.g., forEach, collect, reduce) is invoked. Without a terminal operation, the pipeline never starts processing data, so peek() produces no output.

Exam trap

The trap here is that candidates assume intermediate operations execute eagerly or that peek() works like a standalone print statement, overlooking the fundamental lazy-evaluation contract of streams.

How to eliminate wrong answers

Option A is wrong because parallelism does not prevent peek from printing; it would still print, though possibly interleaved. Option C is wrong because peek cannot be placed after a terminal operation; terminal operations end the pipeline, so any operation after them would cause a compilation error. Option D is wrong because an empty stream would still cause peek to execute (it would simply not print anything), but the question states no output is printed, implying the pipeline never ran.

86
MCQeasy

Refer to the exhibit. What is the result?

A.abc
B.NullPointerException
C.IllegalStateException
D.abcabc
AnswerC

Correct. A stream cannot be reused after a terminal operation.

Why this answer

The code attempts to call `findAny()` on a `Stream` that has already been consumed by a terminal operation (`forEach`). Once a terminal operation is executed on a stream, the stream is closed and cannot be reused. Any subsequent call to a terminal operation on the same stream reference throws `IllegalStateException`.

Option C is correct because the second terminal operation violates the single-use contract of streams.

Exam trap

Oracle Java 17 exams often test the misconception that a stream can be reused like a collection, leading candidates to expect multiple traversals or to overlook the single-use contract enforced by the Stream API.

How to eliminate wrong answers

Option A is wrong because the stream is consumed by the first `forEach`, so the second `forEach` never executes, and `abc` is printed only once, not as the final result. Option B is wrong because `NullPointerException` would only occur if the stream source or an element were null, but here the stream is valid and the elements are non-null strings. Option D is wrong because `abcabc` would require the stream to be traversed twice, which is impossible since a stream cannot be reused after a terminal operation.

87
MCQhard

A stream pipeline filters strings, sorts them, and returns the first match: .filter(s -> s.length() > 3).sorted().findFirst(). This is inefficient because sorted() processes all elements. Which alternative achieves the same result with better performance?

A..filter(s -> s.length() > 3).min(Comparator.naturalOrder())
B..filter(s -> s.length() > 3).sorted().limit(1).findFirst()
C..filter(s -> s.length() > 3).parallel().sorted().findFirst()
D..filter(s -> s.length() > 3).sorted().collect(Collectors.toList()).get(0)
AnswerA

min() uses a reduction that processes each element once, maintaining the minimum without sorting.

Why this answer

`min(Comparator.naturalOrder())` is a terminal operation that finds the smallest element according to natural ordering without sorting the entire stream. It uses a single pass reduction, which is O(n) in time complexity, whereas `sorted().findFirst()` must sort all elements (O(n log n)) before picking the first. This makes `min()` significantly more efficient for this use case.

Exam trap

The trap here is that candidates often assume `sorted().findFirst()` is optimized to stop early, but in Java streams, `sorted()` is a stateful intermediate operation that must process all elements before any downstream operation can begin, making it inherently inefficient for finding a single minimum or maximum.

How to eliminate wrong answers

Option B is wrong because `sorted().limit(1).findFirst()` still requires sorting all elements before limiting, so it does not improve performance over the original. Option C is wrong because `parallel().sorted().findFirst()` adds parallelism overhead and still sorts all elements, and `findFirst()` is a short-circuiting operation that may not benefit from parallelism due to ordering constraints. Option D is wrong because `sorted().collect(Collectors.toList()).get(0)` materializes the entire sorted list into memory before retrieving the first element, which is even less efficient than the original pipeline.

88
MCQmedium

A developer writes: list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); What is the result type and content?

A.Both B and C.
B.Map<T, Long> where T is element type.
C.Map<Object, Long> with number of occurrences of each element.
D.A ConcurrentMap.
AnswerA

This option is self-referential and meaningless; it does not provide a valid description of the result.

Why this answer

Option A, 'Both B and C,' is the correct answer because both statements accurately describe the result. Collectors.groupingBy with Function.identity() and Collectors.counting() produces a Map<T, Long> (where T is the element type) containing the frequency of each element, which can also be described as a Map<Object, Long> with occurrence counts. Options B and C individually are true but incomplete; the question expects selection of the combination.

Option D is incorrect because groupingBy without a map supplier returns a HashMap, not a ConcurrentMap.

Exam trap

The trap is that candidates may focus on individual correct statements and overlook that option A combines both B and C. Recognizing that the result is both a Map<T, Long> and a frequency map is key.

How to eliminate wrong answers

Option B is wrong because it is actually correct, but the question requires selecting both B and C, so B alone is incomplete. Option C is wrong because it is also correct, but again incomplete on its own. Option D is wrong because `Collectors.groupingBy` by default produces a `HashMap` (or a mutable `Map`), not a `ConcurrentMap`; to get a `ConcurrentMap`, you must use `groupingByConcurrent` or supply a `ConcurrentMap` factory via the overloaded `groupingBy` method.

89
MCQmedium

Refer to the exhibit. What is the output?

A.Count: 2
B.Count: 3
C.Count: 1
D.Count: 4
AnswerA

Correct. The filter removes all elements equal to 'A', leaving only non-'A' elements. The exhibit shows exactly two such elements, so the count is 2.

Why this answer

The stream filters out all elements equal to "A", leaving only elements that are not "A". Based on the list in the exhibit, there are exactly two such elements (e.g., "B" and "C"), so the count is 2.

Exam trap

The trap here is that candidates often forget to account for the filter predicate or misread the list contents, leading them to count all elements or assume a different number of non-'A' elements without carefully tracing the stream operations.

How to eliminate wrong answers

Option B (Count: 3) is wrong because it assumes the list has three non-'A' elements, but the correct count is 2, meaning the list either has only two non-'A' elements or includes a distinct() operation that reduces duplicates. Option C (Count: 1) is wrong because it underestimates the number of non-'A' elements; the filter does not remove all elements, only those equal to 'A'. Option D (Count: 4) is wrong because it ignores the filter entirely, counting all elements including 'A's, which is not what the stream does.

← PreviousPage 2 of 2 · 89 questions total

Ready to test yourself?

Try a timed practice session using only Working with Streams and Lambda Expressions questions.