The 30 second answer
You get IllegalStateException for a duplicate key when the two-argument collector sees the same word twice. Use the three-argument toMap with a merge function like Integer sum, or groupingBy with counting, which gives Long counts. Also remember toMap throws on null values, so filter or handle those first.
Could you say this in an interview?
**IllegalStateException** (duplicate key) when collected. Use the 3-arg form toMap(w -> w, w -> 1, Integer::sum) or groupingBy(w -> w, counting()) (gives Long). Also note toMap throws NPE on null values.
Map<String, Integer> counts = words.stream()
.collect(Collectors.toMap(w -> w, w -> 1, Integer::sum));
Map<String, Long> counts2 = words.stream()
.collect(Collectors.groupingBy(w -> w, Collectors.counting()));
Sources (1)
- Collectors.toMap / groupingBydocs.oracle.com