hashMap中如果里面有对用的key,则给value追加数据
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);
}
打印
x: [1]
y: [2]
x: [1, 2]
y: [3]
{1=[1, 2, 3]}

浙公网安备 33010602011771号