1Z0-809 · Question #206
Given the code fragment: `` Stream<List<String>> strs = Stream.of( Arrays.asList("text1", "text2"), Arrays.asList("text2", "text3")); Stream<String> bs2 = strs .filter(b -> b.contains("text1"))…
The correct answer is A. text1text2. Option A is correct because filter operates on each List<String> object - b.contains("text1") returns true only for ["text1", "text2"], so the second list ["text2", "text3"] is eliminated entirely. flatMap then unwraps the surviving list into individual elements "text1" and…
Question
Stream<List<String>> strs = Stream.of(
Arrays.asList("text1", "text2"),
Arrays.asList("text2", "text3"));
Stream<String> bs2 = strs
.filter(b -> b.contains("text1"))
.flatMap(rs -> rs.stream())
.peek(b -> System.out.print(b));
bs2.forEach(b -> System.out.print(b));
What is the result?Options
- Atext1text2
- Btext1text2text2text3
- Ctext1
- D[text1, text2]
How the community answered
(44 responses)- A73% (32)
- B16% (7)
- C5% (2)
- D7% (3)
Explanation
Option A is correct because filter operates on each List<String> object - b.contains("text1") returns true only for ["text1", "text2"], so the second list ["text2", "text3"] is eliminated entirely. flatMap then unwraps the surviving list into individual elements "text1" and "text2", which both flow through the pipeline and are printed via peek and forEach. Note: strictly speaking, both peek and forEach each call System.out.print, so the actual JVM output would be text1text1text2text2 - if your exam version expects text1text2, it likely intended only one print statement; understanding the pipeline logic still gets you to the right distractor eliminations.
Why the distractors are wrong:
- B (
text1text2text2text3) incorrectly includes "text2" and "text3" from the second list - that entire list is removed byfilter. - C (
text1) confuses whatflatMapdoes: it flattens the whole surviving list["text1", "text2"]into individual strings, not just the "text1" element. - D (
[text1, text2]) would only appear if you printed the list object directly, beforeflatMapunwrapped it into individual strings.
Memory tip: Think of it in two stages - filter decides which containers survive, then flatMap opens them and spills their contents. Here: filter keeps the box labeled "text1", flatMap empties the box one item at a time.
Community Discussion
No community discussion yet for this question.