实现方式这里选择了两种常用的方式,都是使用List操作;
第一种实现思路如下:
<1> 原先存放数据的List为recordList,求出共需批量处理的次数;
<2> 新建一个List为list,循环后,将recordList的前maxValue条数据放到list里;
<3> 调用批量处理方法,调用recordList的removeAll方法将list中的数据从recordList中清除;
<4> 调用list.clear方法清除掉list本身的数据;
/** * 批量插入 例如:共1000条数据,第一次批量插入100条,第二次批量插入101到200条,依次插入数据;
* * @param recordList * @param maxValue 批量处理的条数,如1000条 * @return */
private void batchAddRecords(List<String> recordList, int maxValue) { List<String> list = new ArrayList<String>(); int size = recordList.size(); int total = size / maxValue; if (size % maxValue != 0) { total += 1; } for (int i = 0; i < total; i++) { if (i == total - 1) { maxValue = size - (i * maxValue); } for (int j = 0; j < maxValue; j++) { list.add(recordList.get(j)); } // 批量处理的方法 print(list); recordList.removeAll(list); list.clear(); } }
第二种方式设置截取的开始和结束索引
private void batchAddRecords(List<String> recordList, int maxValue) { List<String> list = new ArrayList<String>(); int size = recordList.size(); int total = size / maxValue; if (size % maxValue != 0) { total += 1; }
//如果集合数小于要分组的数量,直接处理
if(recordList.size() < = maxValue) {
// 批量处理的方法 print(list);
}
// 要截取的下标上限
Integer priIndex = 0;
// 要截取的下标下限
Integer lastIndex = 0;
for (int i = 0; i < total; i++) {
priIndex = i*maxValue;
lastIndex = priIndex + maxValue;
//代表最后一次处理 if (i == total - 1) { list = recordList.subList(priIndex , recordList.size);
print(list ); } else {
list = recordList.subList(priIndex , lastIndex);
}
} }
延伸
传入集合数和要分组的数量,返回以该集合数量分组的集合
/**
* 处理list集合--返回map集合
* @param tList (需要截取的集合)
* @param subNum (每次截取的数量)
* @return
*/
public static<T> Map<Integer, List<T>> subListToMap(List<T> tList, Integer subNum) {
// 新的截取到的list集合
Map<Integer, List<T>> newTlsMap = new HashMap<Integer, List<T>>();
// 要截取的下标上限
Integer priIndex = 0;
// 要截取的下标下限
Integer lastIndex = 0;
// 总共需要插入的次数
Integer insertTimes = tList.size() / subNum;
List<T> subNewList = new ArrayList<T>();
// 当入参的集合数量小于分组数,直接返回即可
if (tList.size() <= subNum) {
newTlsMap.put(1, tList);
return newTlsMap;
}
for (int i = 0; i <= insertTimes; i++) {
priIndex = subNum * i;
lastIndex = priIndex + subNum;
// 判断是否是最后一次
if (i == insertTimes) {
subNewList = tList.subList(priIndex, tList.size());
} else { // 非最后一次
subNewList = tList.subList(priIndex, lastIndex);
}
if (subNewList.size() > 0) {
newTlsMap.put(i, subNewList);
}
}
return newTlsMap;
}
注意subList(int fromIndex,int toIndex)
参数说明:
因篇幅问题不能全部显示,请点此查看更多更全内容