数组处理,去重&合并相同key的值

背景:

上游返回的 skuIdList 存在相同的Id,skuCount数组与skuID一一对应

处理结果:skuIdList 去重,对应的count总和要加起来,对应的 originalPriceList 和 subtotalPriceList 不变

代码:

Groovy 复制代码
import groovy.json.JsonSlurper
def skuIdList = new JsonSlurper().parseText('["472262851","472302672","472284575","472262851"]');
//logs.add('skuIdList:\n' + skuIdList.toString());
def applySkuList = [];
def originalPriceList = new JsonSlurper().parseText("[0.03,510.0,51.0,0.03]");
def subtotalPriceList = new JsonSlurper().parseText("[0.21,3570.0,408.0,0.21]");
def skuCountList = new JsonSlurper().parseText("[7,7,8,7]");
def parentPackageId = 5008466108;
 
def skuIdCountMap = [:];
def originalPriceList2 =[];
def subtotalPriceList2 =[];
//通过map去重skuID,并重新写对应价格的数组,使其一一对应
for (int i = 0; i < skuIdList.size(); i++) {
    def currentSkuId = skuIdList[i];
    def currentCount = skuCountList[i];
    if(skuIdCountMap.containsKey(currentSkuId)){
        skuIdCountMap[currentSkuId] += currentCount;
    } else {
        skuIdCountMap[currentSkuId] = currentCount; 
        originalPriceList2.add(originalPriceList[i]);
        subtotalPriceList2.add(subtotalPriceList[i]);
    }
}
/*
遍历skuIdCountMap
分别把skuID 与 对应count 写入2个数组
*/
def skuIDs = [];
def skuCounts = [];
for (String key : skuIdCountMap.keySet()) {
   skuCounts.add(skuIdCountMap[key])
    skuIDs.add(key);
}
println skuIdCountMap;
println originalPriceList2;
println subtotalPriceList2;
println skuIDs;
println skuCounts;

运行结果

java 复制代码
[472262851:14, 472302672:7, 472284575:8]
[0.03, 510.0, 51.0]
[0.21, 3570.0, 408.0]
[472262851, 472302672, 472284575]
[14, 7, 8]
相关推荐
我是咸鱼不闲呀20 分钟前
力扣Hot100系列19(Java)——[动态规划]总结(上)(爬楼梯,杨辉三角,打家劫舍,完全平方数,零钱兑换)
java·leetcode·动态规划
加油,小猿猿1 小时前
Java开发日志-双数据库事务问题
java·开发语言·数据库
yuluo_YX1 小时前
Reactive 编程 - Java Reactor
java·python·apache
山岚的运维笔记1 小时前
SQL Server笔记 -- 第20章:TRY/CATCH
java·数据库·笔记·sql·microsoft·sqlserver
南极企鹅2 小时前
springBoot项目有几个端口
java·spring boot·后端
清风拂山岗 明月照大江2 小时前
Redis笔记汇总
java·redis·缓存
xiaoxue..2 小时前
合并两个升序链表 与 合并k个升序链表
java·javascript·数据结构·链表·面试
忧郁的Mr.Li2 小时前
SpringBoot中实现多数据源配置
java·spring boot·后端
yq1982043011562 小时前
静思书屋:基于Java Web技术栈构建高性能图书信息平台实践
java·开发语言·前端
一个public的class2 小时前
你在浏览器输入一个网址,到底发生了什么?
java·开发语言·javascript