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
1 <= size <= 10^40 <= list.length <= 10^5- The last chunk may have fewer elements than
size.
Hints
Hint 1
Use IntStream.range(0, size).mapToObj(i -> list.subList(...)) with step = chunkSize.
Follow-up
- Implement using Java Streams only (no loops).
- Support lazy chunking with
Iteratorfor very large collections.- >
---
## String Parsing