问题描述
我有这个代码来获取地图:
I have this code to get map:
List<MyObject> myList = myMethod.getList();
myList.stream().collect(
Collectors.toMap(
MyObject::getKey,
MyObject::getValue,
(e1, e2) -> {
System.out.println("Duplicate keys !!!");
return e1;
},
LinkedHashMap::new
)
);
如何使用重复键打印重复密钥消息?
how i can print message "Duplicate keys" with duplicate key?
推荐答案
使用当前代码,您将收到消息Duplicate keys,其中包含 MyObject
列表,其中包含至少2个 MyObject 具有与 getKey()
的值相等的对象,例如 Arrays.asList(new MyObject(foo,bar),新的MyObject(foo,bar2))
。
With your current code, you will get the message "Duplicate keys" with a list of MyObject
which contains at least 2 instances of MyObject
that have equal objects as value for getKey()
, for example Arrays.asList(new MyObject("foo", "bar"), new MyObject("foo", "bar2"))
.
到目前为止,无法获得相应的密钥,您目前获得的密钥来自merge函数的实际上是2个值,这些值使用相同的键映射,需要合并以保留相应键的一个值。
Up to now it is not possible to get the corresponding key, what you currently get from the merge function are actually 2 values mapped with the same key that need to be merged to keep only one value for the corresponding key.
您的问题已在 Java 9 中修复,请参阅了解更多详细信息,相应的修复将允许我们从合并功能获取密钥和要合并的值。
Your problem is a known issue that is fixed in Java 9 see JDK-8040892 for more details, the corresponding fix will allow us to get from the merge function both the key and the values to merge.
另见
这篇关于Collectors.toMap具有相同的键(打印相同的键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!