This is really a question about a minor detail, but I'm under the impression to get something wrong here. If you add duplicate keys using Collectors.toMap-method it throws an Exception with message "duplicate key ". Why is the value reported and not the key? Or even both? This is really misleading, isn't it?
Here's a little test to demonstrate the behaviour:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class TestToMap {
public static void main(String[] args) {
List<Something> list = Arrays.asList(
new Something("key1", "value1"),
new Something("key2", "value2"),
new Something("key3", "value3a"),
new Something("key3", "value3b"));
Map<String, String> map = list.stream().collect(Collectors.toMap(o -> o.key, o -> o.value));
System.out.println(map);
}
private static class Something {
final String key, value;
Something(final String key, final String value){
this.key = key;
this.value = value;
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…