I created a utility method ListUtils.partition(iterable, size)
to partition a potentially large list to a list of smaller lists:
public class ListUtils {
public static <T> List<List<T>> partition(Iterable<T> iterable, int size) {
if (iterable == null) {
return Collections.emptyList();
}
if (size < 1) {
List<T> list = new ArrayList<>();
for (T item : iterable) {
list.add(item);
}
return Arrays.asList(list);
}
List<List<T>> result = new ArrayList<>();
List<T> segment = new ArrayList<>(size);
int i = 0;
for (T item : iterable) {
segment.add(item);
if (++i == size) {
result.add(segment);
segment = new ArrayList<>(size);
i = 0;
}
}
if (i > 0) {
result.add(segment);
}
return result;
}
}
Unit tests:
public class ListUtilsTest {
private <T> List<List<T>> partition(Iterable<T> iterable, int size) {
return ListUtils.partition(iterable, size);
}
@Test
public void testPartitionEmpty() {
assertEquals(Arrays.<List<Object>>asList(), partition(Arrays.asList(), 3));
}
@Test
public void testPartitionNull() {
assertEquals(Arrays.<List<Object>>asList(), partition(null, 3));
}
@Test
public void testPartitionZeroSize() {
List<Integer> orig = Arrays.asList(1, 2, 3);
assertEquals(Arrays.asList(orig), partition(orig, 0));
}
@Test
public void testPartitionNegativeSize() {
List<Integer> orig = Arrays.asList(1, 2, 3);
assertEquals(Arrays.asList(orig), partition(orig, -3));
}
@Test
public void testPartitionInts() {
assertEquals(
Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4),
Arrays.asList(5)),
partition(Arrays.asList(1, 2, 3, 4, 5), 2));
}
@Test
public void testPartitionStrings() {
assertEquals(
Arrays.asList(
Arrays.asList("1", "2"),
Arrays.asList("3", "4"),
Arrays.asList("5")),
partition(Arrays.asList("1", "2", "3", "4", "5"), 2));
}
@Test
public void testPartition_MultipleOfSize() {
assertEquals(
Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4)),
partition(Arrays.asList(1, 2, 3, 4), 2));
}
@Test
public void testPartition_Size1() {
assertEquals(
Arrays.asList(
Arrays.asList(1),
Arrays.asList(2),
Arrays.asList(3),
Arrays.asList(4)),
partition(Arrays.asList(1, 2, 3, 4), 1));
}
@Test
public void testPartition_BiggerSize() {
List<Integer> orig = Arrays.asList(1, 2, 3, 4);
assertEquals(
Arrays.asList(orig),
partition(orig, orig.size() + 11));
}
}
Can you improve this? Are there interesting corner cases I might have missed in the tests?
List
instead of an Iterable and return aList
of subLists of the original list. \$\endgroup\$