兩個Map對應的value值進行加減操作
最近做項目遇到,需要把兩個Map中的value值進行相加或相減,循環(huán)遍歷方法太麻煩,有時候數(shù)據(jù)量大的時候,還會超時。因此使用java8中Stream的Merge方法來處理上述問題,使用如下:文章來源:http://www.zghlxwxcb.cn/news/detail-629159.html
map1.forEach((key,value)->map4.merge(key,value,(v1,v2)->v1+v2));
map3.forEach((key,value)->map5.merge(key,value,(v1,v2)->v2-v1));
實例演示
public static void main(String[] args) {
Map<String,Integer> map1 = new HashMap<>();
map1.put("1",1);
map1.put("2",2);
map1.put("3",3);
map1.put("4",4);
Map<String,Integer> map2 = new HashMap<>();
map2.put("1",1);
map2.put("2",2);
map2.put("3",3);
map2.put("5",5);
Map<String,Integer> map3 = new HashMap<>();
map3.put("1",2);
map3.put("2",4);
map3.put("3",6);
map3.put("5",8);
//以map2為基準,存放相加value值的數(shù)據(jù)集
Map<String, Integer> map4 = new HashMap<>(map2);
//以map1為基準,存放相減value值的數(shù)據(jù)集
Map<String, Integer> map5 = new HashMap<>(map1);
map1.forEach((key,value)->map4.merge(key,value,(v1,v2)->v1+v2));
System.out.println("原始數(shù)據(jù)集1: "+map1);
System.out.println("原始數(shù)據(jù)集2: "+map2);
System.out.println("原始數(shù)據(jù)集3: "+map3);
System.out.println("存放相加value值的數(shù)據(jù)集Map: "+map4);
map3.forEach((key,value)->map5.merge(key,value,(v1,v2)->v2-v1));
System.out.println("原始數(shù)據(jù)集1: "+map1);
System.out.println("原始數(shù)據(jù)集2: "+map2);
System.out.println("原始數(shù)據(jù)集3: "+map3);
System.out.println("存放相加value值的數(shù)據(jù)集Map: "+map5);
}
結果截圖:
從結果圖中可以看出,兩個map進行相加或者相減是可以看出,key值相同的進行value值進行相加減,key值不同的進行追加。文章來源地址http://www.zghlxwxcb.cn/news/detail-629159.html
到了這里,關于Stream兩個Map的value值進行相加/相減,并將合并數(shù)據(jù)集賦值給新Map的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!