fork(3) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.Arrays;
  4. import java.util.List;
  5. import java.util.stream.IntStream;
  6. import java.util.stream.Collectors;
  7.  
  8. class Ideone {
  9. public static void main (String[] args) {
  10. try {
  11. partition(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), 2);
  12. System.out.println("Should have thrown, but did not");
  13. System.out.println("Threw exception as expepcted");
  14. }
  15. System.out.println(partition(
  16. List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
  17. 2));
  18. System.out.println(partition(
  19. List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
  20. 3));
  21. System.out.println(partition(
  22. List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
  23. 4));
  24. }
  25.  
  26. public static List<List<Integer>> partition(
  27. List<Integer> list,
  28. int partitionSize) {
  29. int listSize = list.size();
  30. if (listSize % partitionSize != 0) {
  31. throw new IllegalArgumentException("The size of the list must be "
  32. + "divisible without remainder by the partition size.");
  33. }
  34. final int parts = listSize / partitionSize;
  35. return IntStream.range(0, parts)
  36. .mapToObj(i -> list.subList(2 * i, 2 * i + partitionSize))
  37. .collect(Collectors.toList());
  38. }
  39. }
Success #stdin #stdout 0.09s 34288KB
stdin
Standard input is empty
stdout
Threw exception as expepcted
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]
[[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9]]
[[1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 7, 8]]