import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
Test test = new Test();
ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
ArrayList<ArrayList<String>> arrayLists = test.subList(list,2);
for(ArrayList a:arrayLists){
System.out.println("======");
for(Object b:a){
System.out.println("b = " + b);
}
}
}
/**
* 分割数组
*
* @param userIdList 要分割的数组
* @param num 要分割的长度
* @return
*/
public ArrayList<ArrayList<String>> subList(ArrayList<String> userIdList, int num) {
ArrayList<ArrayList<String>> userIdLists = new ArrayList<>();
int number;
// 当长度小于要分割的长度,直接存入数组中
if (userIdList.size() > num) {
//判断数组中有几个num 即要分割的个数
if (userIdList.size() % num > 0) {
number = userIdList.size() / num + 1;
} else {
number = userIdList.size() / num;
}
// 循环把分割的数组存入 userIdLists 中
for (int i = 0; i < number; i++) {
ArrayList<String> userIds = new ArrayList<>();
// 最后一个数组长度不定
if (i != number - 1) {
for (int j = 0; j < num; j++) {
userIds.add(userIdList.get(i * num + j));
}
} else {
for (int j = 0; j < userIdList.size() - (i * num); j++) {
userIds.add(userIdList.get(i * num + j));
}
}
userIdLists.add(userIds);
}
} else {
userIdLists.add(userIdList);
}
return userIdLists;
}
}
list分割成多个list
最新推荐文章于 2024-07-04 21:45:35 发布