为什么 Collectors.toMap 在重复键错误时报告值而不是键? [英] Why does Collectors.toMap report value instead of key on Duplicate Key error?

查看:28
本文介绍了为什么 Collectors.toMap 在重复键错误时报告值而不是键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这确实是一个关于小细节的问题,但我觉得这里有什么问题.如果您使用 Collectors.toMap-method 它抛出一个带有消息重复键"的异常.为什么报告的是值而不是键?或者两者兼而有之?这真的是误导,不是吗?

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;
        }
    }
}

推荐答案

这被报告为一个错误,参见 JDK-8040892,在 Java 9 中已修复.阅读提交修复此问题a>,新的异常信息将是

This is reported as a bug, see JDK-8040892, and it is fixed in Java 9. Reading the commit fixing this, the new exception message will be

String.format("Duplicate key %s (attempted merging values %s and %s)", k, u, v)

其中 k 是重复键,uv 是映射到同一键的两个冲突值.

where k is the duplicate key and u and v are the two conflicting values mapped to the same key.

这篇关于为什么 Collectors.toMap 在重复键错误时报告值而不是键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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