Java8 toMap异常消息令人困惑 [英] Java8 toMap exception message confusing

查看:159
本文介绍了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

这篇关于Java8 toMap异常消息令人困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆