Chunk Collection into Groups

Difficulty: Easy · Topics: Collections, Streams, Partitioning · Acceptance: 100.0% of 1 submissions

Difficulty: Easy  |  Tags: Collections, Streams, Partitioning

Description

Given a collection (list) of elements and a chunk size n, split the collection into smaller sub-lists, each containing at most n elements.

Implement:

chunk(list, size) → List<List<T>>

Examples

Example 1:

Input:  list = [1, 2, 3, 4, 5], size = 2
Output: [[1, 2], [3, 4], [5]]

Example 2:

Input:  list = ["a", "b", "c", "d"], size = 4
Output: [["a", "b", "c", "d"]]

Example 3:

Input:  list = [1, 2, 3], size = 5
Output: [[1, 2, 3]]

Example 4:

Input:  list = [], size = 3
Output: []

Constraints

Hints

Hint 1

Use IntStream.range(0, size).mapToObj(i -> list.subList(...)) with step = chunkSize.

Follow-up

---

## String Parsing

Practice this problem

Related problems