Drill

ProblemsJava › warmup

Break a list into fixed-size pieces

mediumwarmupArraysJava

A bulk API takes at most a hundred records per call, so a long list has to be handed over in pieces.

chunkList(values: list<int>, perChunk: int) → list<list<int>>

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

List<List<Integer>> chunkList(List<Integer> values, int perChunk) {
    
}

Worked examples

CallResult
chunkList(Main.<Integer>ls(1, 2, 3, 4, 5), 2)Main.<List<Integer>>ls(Main.<Integer>ls(1, 2), Main.<Integer>ls(3, 4), Main.<Integer>ls(5))
chunkList(Main.<Integer>ls(1, 2, 3, 4), 2)Main.<List<Integer>>ls(Main.<Integer>ls(1, 2), Main.<Integer>ls(3, 4))
chunkList(Main.<Integer>ls(1), 5)Main.<List<Integer>>ls(Main.<Integer>ls(1))
chunkList(Main.<Integer>ls(), 2)Main.<List<Integer>>ls()

Hint

Step the index forward by the chunk size and slice, rather than pushing one item at a time.

Reference solution in Java
List<List<Integer>> chunkList(List<Integer> values, int perChunk) {
    List<List<Integer>> result = new ArrayList<>();
    if (perChunk <= 0) return result;
    for (int i = 0; i < values.size(); i += perChunk) {
        result.add(new ArrayList<>(values.subList(i, Math.min(i + perChunk, values.size()))));
    }
    return result;
}

The same problem in another language

More warmup problems in Java