有时候一个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; }