import java.util.ArrayList;
import java.util.List;
/**
* 描述:List拆分操作
*
* @auther husheng
* @date 2020/5/23 1:42
*/
public class ListOperation {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 11; i++) {
list.add(i);
}
System.out.println(list.toString());//[1, 2, 3, 4, 5, 6, 7, 8, 9, 11]
/**
* 對list進行拆分,比如要調用的接口的入參是list,但是限制了大小是2,
* 也就是說一次只能傳2條數據
*/
int size = 2; //定義要拆分的單個list內的元素
/**
* times 表示將對list進行幾次拆分
* list的大小%size 如果能除盡,times的循環次數為list.size()%size
* list的大小%size,如果除不盡,times的循環次數需要多一次, list.size() / size + 1
*/
int times = list.size() % size == 0 ? list.size() / size : list.size() / size + 1;
for (int i = 0; i < times; i++) {
//tempList存放每一次需要當做參數操作check方法的集合
List<Integer> tempList = new ArrayList<Integer>();
//將指定索引數據放入的tempList中
for (int j = i * size; j <= size * (i + 1) - 1; j++) {
if (j <= list.size() - 1) {
tempList.add(list.get(j));
}
System.out.println("tempList: " + tempList);
}
//調用方法
check(tempList);
}
}
/**
* 遍歷list操作,如果list內的個數大於2,則無法進行遍歷操作
*
* @param list
*/
static int i = 1;
public static void check(List<Integer> list) {
if (list.size() > 2) {
System.out.println("入參大於2,無法進行下一步操作");
return;
}
System.out.println("第" + (i++) + "次循環......");
System.out.println("遍歷list開始......");
System.out.println("list-size----" + list.size());
System.out.println("list----" + list);
System.out.println("遍歷結束");
System.out.println("-------------------");
}
}
結果:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
tempList: [1]
tempList: [1, 2]
第1次循環......
遍歷list開始......
list-size----2
list----[1, 2]
遍歷結束
-------------------
tempList: [3]
tempList: [3, 4]
第2次循環......
遍歷list開始......
list-size----2
list----[3, 4]
遍歷結束
-------------------
tempList: [5]
tempList: [5, 6]
第3次循環......
遍歷list開始......
list-size----2
list----[5, 6]
遍歷結束
-------------------
tempList: [7]
tempList: [7, 8]
第4次循環......
遍歷list開始......
list-size----2
list----[7, 8]
遍歷結束
-------------------
tempList: [9]
tempList: [9, 10]
第5次循環......
遍歷list開始......
list-size----2
list----[9, 10]
遍歷結束
-------------------
tempList: [11]
tempList: [11]
第6次循環......
遍歷list開始......
list-size----1
list----[11]
遍歷結束
-------------------