利用Map集合将list集合中数据进行拆分。

本文介绍了一种使用Java HashMap实现的集合拆分方法,通过遍历原集合并根据standardId字段值进行数据分类,最终形成两个子集合:一个包含重复数据,另一个包含非重复数据。此方法适用于需要对混合类型数据集进行高效处理和分类的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时候一个list集合中存在两种类型的数据,正好业务需要将这两类数据进行拆分使用。

 如下代码中orderList为原生的数据集合体。根据standardId字段值来进行区分数据。

 hashMap集合以 standardId为key,tempList 为value;

 

 

/**
 * @param orderList:
 * @return Map<Integer,List<Production>>
 * @title productionEquipmentIsRepeat
 * @description 校验list集合standardID是否有重复,并将集合分成2个集合,1==重复数据集合,2==非重复数据
 * @author 
 * @date 2019/12/18 9:15
 */
private Map<Integer,List<Production>> productionIsRepeat(List<Production> orderList) {
    HashMap<String, List<Production>> hashMap = new HashMap<>();
    for(Production production:orderList){
        if(hashMap.get(production.getStandardId())!=null){ 
            //相同的standardID放入同一个键值对中。
            List<Production> tempList = hashMap.get(production.getStandardId());
            tempList.add(production);
            hashMap.put(production.getStandardId(), tempList);
        }else{
            List<Production> tempList = new ArrayList<>();
            tempList.add(production);
            hashMap.put(production.getStandardId(), tempList);
        }
    }
    //key==1 重复数据集合  key==2  不重复数据集合
    Map<Integer,List<Production>> map = new HashMap<>();
//hashMap.entrySet()该方法并不是返回一个存储数据的集合而是返回此映射所包含的映射关系的set视图。(通俗来讲就是返回一个set集合)这个方法可以读取到其所在的HashMap对象的存储的键值对,而我们经常使用entrySet方法就是用来进行foreach循环的。
    for(Map.Entry<String, List<Production>> entry : hashMap.entrySet()){ 
        if(entry.getValue().size()>1){//遍历set集合,判断集合中value是否大于1,进行分类。
            if(map.get(1) != null){
                List<Production> tempList = map.get(1);
                tempList.addAll(entry.getValue());
            }else{
                map.put(1,entry.getValue());
            }
        }else{
            if(map.get(2) != null){
                List<Production> tempList = map.get(2);
                tempList.addAll(entry.getValue());
            }else{
                map.put(2,entry.getValue());
            }
        }
    }
    return map;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值