将list分割成指定大小的子list

public static void main(String[] args) {
        List integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 6, 5, 4, 7, 8, 5, 2, 14, 56);

        List> chopped = chopped(integers, 5);

        for (List integerList : chopped) {
            System.out.println(integerList);
        }

    }

    // chops a list into non-view sublists of length L
    static  List> chopped(List list, final int L) {
        List> parts = new ArrayList<>();
        final int N = list.size();
        for (int i = 0; i < N; i += L) {
            parts.add(new ArrayList<>(
                    list.subList(i, Math.min(N, i + L)))
            );
        }
        return parts;
    }
输出结果:
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 6]
[5, 4, 7, 8, 5]
[2, 14, 56]

你可能感兴趣的:(积累分享)