Convert a list of objects to a Map, handling duplicate keys. Compare loops, toMap, toMap with merge, and groupingBy.
Problem
Convert List<Employee> to a map keyed by department. Interviewers ask what happens with duplicate keys and how to choose what to keep.
record Emp(String name, String dept, int salary) {}Approach 1: Plain loop (Java 7 style)
Last write silently wins.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class ToMapLoop {
static Map<String, Emp> byDept(List<Emp> emps) {
Map<String, Emp> map = new HashMap<>();
for (Emp e : emps) map.put(e.dept(), e);
return map;
}
}Approach 2: Collectors.toMap without a merge function (throws on duplicates)
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
class ToMapStrict {
static Map<String, Emp> byName(List<Emp> emps) {
return emps.stream().collect(Collectors.toMap(Emp::name, Function.identity())); // fine: names are unique
}
static String byDeptFails(List<Emp> emps) {
try {
emps.stream().collect(Collectors.toMap(Emp::dept, Function.identity()));
return "no error";
} catch (IllegalStateException e) {
return "IllegalStateException: " + e.getMessage();
}
}
}Approach 3: toMap with a merge function (decide explicitly)
Keep the highest-paid employee per department, in a sorted map.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.Comparator;
class ToMapMerge {
static Map<String, Emp> topPaidPerDept(List<Emp> emps) {
return emps.stream().collect(Collectors.toMap(Emp::dept, Function.identity(),
BinaryOperator.maxBy(Comparator.comparingInt(Emp::salary)), TreeMap::new));
}
}Approach 4: groupingBy when you want every value (Map<K, List>)
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
class ToMapGrouping {
static Map<String, List<String>> namesByDept(List<Emp> emps) {
return emps.stream().collect(Collectors.groupingBy(Emp::dept, TreeMap::new,
Collectors.mapping(Emp::name, Collectors.toList())));
}
}
class ToMapDemo {
public static void main(String[] args) {
List<Emp> emps = List.of(new Emp("Asha", "Eng", 200), new Emp("Ravi", "Eng", 180), new Emp("Meera", "HR", 90));
System.out.println(new java.util.TreeMap<>(ToMapLoop.byDept(emps)).get("Eng").name()); // Ravi (last wins)
System.out.println(ToMapStrict.byName(emps).keySet().size()); // 3
System.out.println(ToMapStrict.byDeptFails(emps)); // IllegalStateException: Duplicate key Eng ...
System.out.println(ToMapMerge.topPaidPerDept(emps)); // {Eng=Emp[name=Asha...], HR=Emp[name=Meera...]}
System.out.println(ToMapGrouping.namesByDept(emps)); // {Eng=[Asha, Ravi], HR=[Meera]}
}
}Feasible → optimal
All O(n). The loop hides data loss; toMap without a merge function fails fast on duplicates (good for keys that must be unique); toMap with a merge function makes the business rule explicit; groupingBy keeps all values. Also remember toMap throws NullPointerException on null values.
Follow-up questions interviewers ask
Try answering each one before you open it.
Related (same pattern): count employees per department and average salary per department.
groupingBy(Emp::dept, counting()) and groupingBy(Emp::dept, averagingInt(Emp::salary)); both at once with teeing (Java 12) or summarizingInt (count, sum, min, average, max in one pass).
Related (same pattern): partition employees into high and low earners.
partitioningBy(e -> e.salary() > 150, mapping(Emp::name, toList())) returns a Map<Boolean, List<String>> with both keys always present, unlike groupingBy.