Java8 toMap异常消息令人困惑
遇到此异常:
java.lang.IllegalStateException: Duplicate key 50
我查看了每个使用该代码的地图,并且没有这样的密钥
它花了我一段时间,但我发现了问题但是它很容易让人感到困惑而且很难解释为什么他们不这样做呢
I looked over every map that is using that code, and there is no such key It took me a while but I found the problem but it is confusing and very problematic to understand don't know why they did it like this
这是我的代码:
List<Person> listOfPeople = new LinkedList<Person>();
Map<String, Integer> myMap = listOfPeople
.stream()
.collect(Collectors.toMap(
Person::getNameInString,
Person::getAgeInInt
)
);
我的地图是String to Integer,所以50来自???
My map is String to Integer, so were did 50 came from???
答案是:
我带了一些挖掘找到引起这个问题的相关输入。
The Answer is that:
I took me some digging finding the relevant input causing this problem.
事实证明我有两个同名的人,
为什么不打印:
It turns out that I had two people with the same name,
So why not print:
java.lang.IllegalStateException: Duplicate key "Ohad Edelstein"
例如。
他们得到50???!
50岁是第一个Ohad Edelstein的年龄!
were did they get 50?!?!
50 is the age, of the first "Ohad Edelstein"!
我是怎么做到的?
我查看了文档,发现了这种方法:
How did I get that? I looked in the documentation and found this method:
private static <T> BinaryOperator<T> throwingMerger() {
return (u,v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); };
}
什么是你和v?
这是在 HashMap中调用它的方法
remappingFunction.apply(old.value, value)
打印价值有什么意义?!?!为什么不写类似
What is the point of printing the value?!?! why not write something like
java.lang.IllegalStateException: Duplicate key "Ohad Edelstein", first value 50 second value 35
任何方式,希望它会阻止其他人至少部分挫败感
Any way, hope it will prevent others from at least part of the frustration
仅供参考,处理异常问题 - 如果你对它没问题,你可以看看这个答案:
使用流生成地图时忽略重复
FYI, to handle the exception issue - if you are fine with it, you can take a look at this answer:
Ignore duplicates when producing map using streams