Collectors.toMap具有相同的键(打印相同的键) [英] Collectors.toMap with same keys(print same key)

查看:959
本文介绍了Collectors.toMap具有相同的键(打印相同的键)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码来获取地图:

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?

推荐答案


如何使用重复键打印消息重复密钥?

how i can print message "Duplicate keys" with duplicate key?

使用当前代码,您将收到消息Duplicate keys,其中包含 MyObject 列表,其中包含至少2个<的实例code> 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")).


如何获取相应的密钥?

How to get the corresponding key?

到目前为止,无法获得相应的密钥,您目前获得的密钥来自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 中修复,请参阅 JDK-8040892 了解更多详细信息,相应的修复将允许我们从合并功能获取密钥和要合并的值。

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报告值而不是重复键错误上的键?

这篇关于Collectors.toMap具有相同的键(打印相同的键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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