CCNA Streams Lambdas Questions

11 of 86 questions · Page 2/2 · Streams Lambdas topic · Answers revealed

76
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.of throws NPE for null; ofNullable returns empty for null; orElseThrow throws exception if empty; ifPresent does nothing for empty; get throws NoSuchElementException for empty.

77
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

Option B is correct because 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.

78
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 can lead to non-deterministic results in parallel streams because shared mutable state creates race conditions.

79
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

Correctly groups, filters by average, then sums.

Why this answer

Option A is correct because 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.

80
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

Option B is correct because HashMap is not thread-safe, and the default toMap collector uses a non-concurrent map which can be corrupted in parallel stream. Using ConcurrentHashMap as the map supplier ensures thread-safe concurrent accumulation. Option A is wrong because the merge function is associative and compatible with parallel reduction.

Option C is wrong because using parallelstream and then sequential() would lose parallelism, though it would work. Option D is wrong because forEach with put might cause race conditions even with ConcurrentHashMap if not using merge.

81
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.

82
Drag & Dropmedium

Order the steps to properly implement the Singleton pattern with lazy initialization in Java.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

Double-checked locking reduces synchronization overhead. The volatile keyword ensures visibility of the instance across threads.

83
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

After the first terminal operation (forEach), the stream is consumed. Any further operation on the same stream throws IllegalStateException.

84
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

Using min() is a short-circuiting terminal operation that finds the minimum without sorting the entire stream, thus improving performance.

85
MCQmedium

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

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

Both describe the result accurately: it maps each distinct element to its count.

Why this answer

The correct answer is A because both B and C accurately describe the result. The code uses `Collectors.groupingBy(Function.identity(), Collectors.counting())`, which returns a `Map<T, Long>` where `T` is the element type of the stream. The map contains the number of occurrences of each distinct element, effectively a frequency count.

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

Exam trap

The trap here is that candidates often assume only one answer is correct, but the question explicitly states 'Both A and B' as an option, testing whether you recognize that both B and C are true statements about the result type and content.

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.

86
MCQmedium

Refer to the exhibit. What is the output?

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

A is correct: there are two even numbers (2 and 4).

Why this answer

The correct output is 'Count: 2' because the stream filters even numbers (2,4) and counts them, resulting in 2.

← PreviousPage 2 of 2 · 86 questions total

Ready to test yourself?

Try a timed practice session using only Streams Lambdas questions.