Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. public static <T> Stream<List<T>> batches(List<T> source, int length) {
  2. if (length <= 0)
  3. throw new IllegalArgumentException("length = " + length);
  4. int size = source.size();
  5. if (size <= 0)
  6. return Stream.empty();
  7. int fullChunks = (size - 1) / length;
  8. return IntStream.range(0, fullChunks + 1).mapToObj(
  9. n -> source.subList(n * length, n == fullChunks ? size : (n + 1) * length));
  10. }
  11.  
  12. public static void main(String[] args) {
  13. List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14);
  14.  
  15. System.out.println("By 3:");
  16. batches(list, 3).forEach(System.out::println);
  17.  
  18. System.out.println("By 4:");
  19. batches(list, 4).forEach(System.out::println);
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement