有时候,有需求如下:需要对一个list进行分包,比如100个数据,分成10包,每个包10个数据。
代码实现如下:
List<Integer> ListData = new ArrayList<>();
ListData.add(1);
ListData.add(2);
ListData.add(3);
ListData.add(4);
int iPacket = 2;
int iCount = ListData.size()/iPacket;
int iRemaind = ListData.size() % iPacket;
List<List<Integer>> AverageInfo = new ArrayList<>();
for (int i =0;i<iCount;i++){
List<Integer> tempInfo =ListData.subList(i*iPacket,(i+1)*iPacket);
AverageInfo.add(tempInfo);
}
if (iRemaind>0){
List<Integer> tempInfo = ListData.subList(iCount*iPacket,iCount*iPacket+iRemaind);
AverageInfo.add(tempInfo);
}
for (List<Integer> item :AverageInfo){
Log.i("test","listAverage");
for (Integer i :item){
Log.i("test","item:"+i);
}
}
输出结果如下:成功实现了分包