1Z0-829 Working with Streams and Lambda Expressions Practice Question
A method receives a List<String> and needs to transform it to a Map where the key is the first three characters of each string and the value is the string itself. If two strings have the same prefix, the later one should override the earlier. Which collector achieves this?
⚠ Common exam trap
The trap here is that candidates often pick `toMap` without a merge function (Option B) or `groupingBy` (Option A), forgetting that duplicate keys cause exceptions or produce the wrong map type, respectively.
Answer choices
Why each option matters
Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.
Correct answer & explanation
✓
Collectors.toMap(s -> s.substring(0,3), Function.identity(), (a,b) -> b)
`Collectors.toMap` with a merge function `(a, b) -> b` ensures that when duplicate keys (first three characters) occur, the later string in the stream order replaces the earlier one. The merge function is invoked on key collision, and returning `b` (the second argument) keeps the later value, satisfying the requirement.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
Collectors.groupingBy(s -> s.substring(0,3))
Why it's wrong here
Returns Map<String, List<String>>, not single values.
- ✗
Collectors.toMap(s -> s.substring(0,3), Function.identity())
Why it's wrong here
Throws IllegalStateException if duplicate keys exist.
- ✗
Collectors.toConcurrentMap(s -> s.substring(0,3), Function.identity())
Why it's wrong here
Also throws on duplicate keys.
- ✓
Collectors.toMap(s -> s.substring(0,3), Function.identity(), (a,b) -> b)
Why this is correct
Correct: The merge function (a,b) -> b keeps the later value.
Go deeper
Related to this question
About these practice questions
This 1Z0-829 question is part of Courseiva's 513-question bank — original exam-style content with full explanations and wrong-answer analysis, never real exam questions or exam dumps. Learn why practice questions differ from exam dumps →
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
This 1Z0-829 practice question is part of Courseiva's free Oracle certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the 1Z0-829 exam.