hashMap中如果里面有对用的key,则给value追加数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public static void main(String[] args) {
    Map<Integer, List<Integer>> type2OtherData = new HashMap<>();
    List<Integer> i = new ArrayList<>();
    i.add(1);
    type2OtherData.merge(1,i, (x,y) -> {
        // x 为map中已有key对应的value值
        System.out.println("x: " + x);
        // y 为此时输入的value,也就是此处的 i
        System.out.println("y: " + y);
        // 我这里是追加操作,自己可以根据情况修改
        x.addAll(y);
        return x;
    });
    List<Integer> ii = new ArrayList<>();
    ii.add(2);
    type2OtherData.merge(1,ii, (x,y) -> {
        System.out.println("x: " + x);
        System.out.println("y: " + y);
        x.addAll(y);
        return x;
    });
    List<Integer> iii = new ArrayList<>();
    iii.add(3);
    type2OtherData.merge(1,iii, (x,y) -> {
        System.out.println("x: " + x);
        System.out.println("y: " + y);
        x.addAll(y);
        return x;
    });
    System.out.println(type2OtherData);
}

  打印

1
2
3
4
5
x: [1]
y: [2]
x: [1, 2]
y: [3]
{1=[1, 2, 3]}

  


__EOF__

本文作者东峰叵.com
本文链接https://www.cnblogs.com/databank/p/18740362.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   东峰叵,com  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示