nerdexam
Oracle

1Z0-829 · Question #25

Given the code fragment: Stream<String> s1 = Stream.of("A", "B", "C", "B"); Stream<String> s2 = Stream.of("A", "D", "E", "B"); Stream.concat(s1, s2).parallel().distinct().forEach(element ->…

The correct answer is D. ABBDE // the order of elements is unpredictable. Option D as stated appears to be an error in the answer key - the actual correct answer should be C. Here's why: Stream.concat(s1, s2) produces ["A","B","C","B","A","D","E","B"]. After .distinct(), duplicates are removed, leaving exactly five unique elements: A, B, C, D, E…

Working with Streams and Lambda expressions

Question

Given the code fragment: Stream<String> s1 = Stream.of("A", "B", "C", "B"); Stream<String> s2 = Stream.of("A", "D", "E", "B"); Stream.concat(s1, s2).parallel().distinct().forEach(element -> System.out.print(element)); What is the result?

Options

  • AADEABCB // the order of element is unpredictable
  • BABCE
  • CABCDE // the order of elements is unpredictable
  • DABBDE // the order of elements is unpredictable

How the community answered

(35 responses)
  • A
    17% (6)
  • B
    9% (3)
  • C
    6% (2)
  • D
    69% (24)

Explanation

Option D as stated appears to be an error in the answer key - the actual correct answer should be C.

Here's why: Stream.concat(s1, s2) produces ["A","B","C","B","A","D","E","B"]. After .distinct(), duplicates are removed, leaving exactly five unique elements: A, B, C, D, E. Because .parallel() is applied before .forEach(), the terminal operation runs across threads with no guaranteed encounter order, so the print sequence is unpredictable - matching option C exactly.

Why the other choices fail:

  • A (ADEABCB) contains 7 elements and preserves duplicates, ignoring that distinct() eliminates them.
  • B (ABCE) is missing D, which is a distinct element present in s2.
  • D (ABBDE) contains a duplicate B and omits C entirely - impossible after distinct(), which guarantees each element appears at most once regardless of parallelism.

Memory tip: Think of distinct() as a guarantee, not a hint - it always produces unique elements even in parallel pipelines (it uses a thread-safe ConcurrentHashMap internally). The only thing parallelism affects here is the print order via forEach, never the correctness of distinct(). If your answer has duplicates after distinct(), eliminate it immediately.

Topics

#Stream.concat()#parallel()#distinct()#stream ordering

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice