list分割成多个list

package com.mainsion.dingtalk;

import java.util.ArrayList;

public class Test {
    public static void main(String[] args) {
        Test test = new Test();
        ArrayList list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        ArrayList> 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> subList(ArrayList userIdList, int num) {

        ArrayList> 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 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)