Partition List in Java using Stream
In Java 8, patitioning a List to chunks according to given chunk size.
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ListHelper {
public static <T> List<List<T>> partition(List<T> list, int size) {
if (list == null) throw new NullPointerException("list is null");
if (size <= 0) throw new IllegalArgumentException("size is negative");
Collection<List<T>> temp = IntStream.range(0, list.size())
.boxed()
.collect(Collectors.groupingBy(index -> index / size,
Collectors.mapping(list::get, Collectors.toList())))
.values();
return new ArrayList<>(temp);
}
}