OneBite.Dev - Coding blog in a bite size

split an array into smaller arrays in java

Code snippet on how to split an array into smaller arrays in java

  List<List<Integer>> splitList = new ArrayList<>();
 
  int groupSize = 5;
  for(int i = 0; i < array.length; i += groupSize ) {
      List<Integer> subList = new ArrayList<>();
      int limit = Math.min(array.length, i + groupSize);
      for(int j = i; j < limit; j++) {
          subList.add(array[j]);
      }
      splitList.add(subList);
  }

This code splits an array into smaller arrays. It begins by creating an array list ‘splitList’ to store the smaller arrays. Next it sets the ‘groupSize’, which is the size of each of the smaller arrays. It then starts a loop, where it checks if the index of the array is smaller than the length of the array and adds the groupSize to the index each iteration. In the loop, it creates a new array list ‘subList’ to store the smaller array. It then checks if the index and groupSize are greater than the array size and takes the minimum of the two. It then starts another loop, which takes the elements from the array and adds it to the subList. It then adds the subList to the splitList and the loop exits. Unlike the first loop, this one exits when the limit (index + groupSize) is reached.

java