I'm trying to convert a list of objects to a Map
using Java Streams:
List<String> list = List.of("a", "b", "a");
Map<String, Integer> map = list.stream()
.collect(Collectors.toMap(s -> s, String::length));
This throws:
java.lang.IllegalStateException: Duplicate key a (attempted merging values 1 and 1)
I expected it to just create a map with unique keys, but I forgot that my list has duplicates. What's the correct way to handle this if duplicates may occur? Is there a way to merge them, or just keep the first one?
Answer
Make sure you have 'distinct' values:
Map<String, Integer> map = list.stream()
.distinct()
.collect(Collectors.toMap(s -> s, String::length));