简体   繁体   English

Map.merge 不会向 ArrayList 添加值

[英]Map.merge doesnt add value to ArrayList

i have a map and try to add value to an arraylist.我有一张地图并尝试向数组列表添加值。

Example: Key:1 Value:ArrayList(1), Key:2 Value:ArrayList(2), Key:3 Value:ArrayList(3,3)示例:Key:1 Value:ArrayList(1), Key:2 Value:ArrayList(2), Key:3 Value:ArrayList(3,3)

    String ss = "1233";
    char[] a = ss.toCharArray();
    Map<Character, ArrayList<Character>> mymap = new LinkedHashMap<>();
    for (char c : a) {
        mymap.merge(c,new ArrayList<>(c), (o,n)->{
          o.addAll(n); return o;
        });
    }

but it doenst work, the value (ArrayList) is allways empty.但它确实有效,值 (ArrayList) 始终为空。 What am I doing wrong?我究竟做错了什么? Debuger output:调试器输出:

mymap = {LinkedHashMap@418}  size = 3
        {Character@599} 1 -> {ArrayList@600}  size = 0
        key = {Character@599} 1
        value = {ArrayList@600}  size = 0
        {Character@604} 2 -> {ArrayList@605}  size = 0
        key = {Character@604} 2
        value = {ArrayList@605}  size = 0
        {Character@609} 3 -> {ArrayList@610}  size = 0
        key = {Character@609} 3
        value = {ArrayList@610}  size = 0
new ArrayList<>(c)

is not doing what you think it is.不是在做你认为的事情。 It is creating an empty list, with an initial capacity related to the integer value of the character.它正在创建一个空列表,其初始容量与字符的整数值相关。

It is not creating a list with a single element.不是用单个元素创建列表。

You are putting empty ArrayList s in the Map , and then you merge empty ArrayList s, which results in empty ArrayList s.您将空的ArrayList放入Map ,然后合并空的ArrayList ,这会导致空的ArrayList

Try:尝试:

mymap.merge(c,new ArrayList<>(Arrays.asList(c)), (o,n)->{
    o.addAll(n); return o;
});

or或者

mymap.merge(c,new ArrayList<>(List.of(c)), (o,n)->{
    o.addAll(n); return o;
});

Now the Map will contain:现在Map将包含:

{1=[1], 2=[2], 3=[3, 3]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM