如何使用 Java 将 List<Integer> 转换为 List<List<Integer>>?固定内部列表的大小

How to convert List<Integer> to List<List<Integer>> using Java? Fixing the size of inner list

我有要批量处理的号码列表。

example 1:

input1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] //(List of number)
input2 = 5 //(Batch size)
output = [[1, 2, 3, 4, 5], [6, 7, 8, 9]]

example 2:

input1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]//(List of number) 
input2 = 5//(Batch size)
output = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

这是一个使用 java 流的示例,

 public static void main(String[] args) throws Exception {

        List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));
        int batchSize = 5;
        AtomicInteger ai = new AtomicInteger();

        Collection<List<Integer>> chunkedOrders = list.stream()
                .collect(Collectors.groupingBy(item -> ai.getAndIncrement() / batchSize)).values();

        System.out.println("Your innerlist = " + chunkedOrders);

        chunkedOrders.forEach(chunk -> {
            System.out.println("Processing" + " " + chunk.size() + " " + " data, sublist = " + chunk);

        });

    }

输出:

Your innerlist = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11]]
Processing 5  data, sublist = [1, 2, 3, 4, 5]
Processing 5  data, sublist = [6, 7, 8, 9, 10]
Processing 1  data, sublist = [11]
public class Solution {

    public static <T> List<List<T>> breaks(List<T> tList, int length) {
        if (length <= 0)
            throw new IllegalArgumentException(
                    "The chosen length is less than or equal to zero: " + length
            );
        int size = tList.size();
        if (size <= 0)
            return new ArrayList<>();
        int fullChunks = (size - 1) / length;
        return IntStream.range(0, fullChunks + 1).mapToObj(
                n -> tList.subList(n * length, n == fullChunks ? size : (n + 1) * length)
        ).collect(Collectors.toList());
    }

    public static void main(String args[]) {

        // Original list
        List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14);
        // Printing of the original list
        System.out.println(list1);
        // Broken list
        List<List<Integer>> list2 = breaks(list1,5);
        // Print of the broken list
        System.out.println(list2);

    }

}