fork(1) download
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. class Ideone {
  5. public static void main (String[] args) {
  6. try {
  7. partition(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), 2);
  8. System.out.println("Should have thrown, but did not");
  9. System.out.println("Threw exception as expepcted");
  10. }
  11. System.out.println(partition(
  12. List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
  13. 2));
  14. System.out.println(partition(
  15. List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
  16. 3));
  17. System.out.println(partition(
  18. List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
  19. 4));
  20. }
  21.  
  22. public static List<List<Integer>> partition(
  23. List<Integer> list,
  24. int partitionSize) {
  25. final int listSize = list.size();
  26. if (listSize % partitionSize != 0) {
  27. throw new IllegalArgumentException("The size of the list must be "
  28. + "divisible without remainder by the partition size.");
  29. }
  30.  
  31. final List<List<Integer>> partition = new ArrayList<>();
  32. for (int start = 0; start < listSize; start += partitionSize) {
  33. partition.add(list.subList(start, start + partitionSize));
  34. }
  35. return partition;
  36. }
  37. }
Success #stdin #stdout 0.06s 32468KB
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], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]