Divides given array on sub arrays - Java Collection Framework

Java examples for Collection Framework:Array Sub Array

Description

Divides given array on sub arrays

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    /**//from w w  w  .  j ava  2 s . c om
     * Divides given array on sub arrays
     * 
     * @param arr
     *            the original array that be divided on sub arrays
     * @param subArrSize
     *            the size of each sub array
     * @return the java.util.List<Integer[]> of sub arrays
     */
    public static List<Integer[]> getSubarraysList(Integer[] arr,
            int subArrSize) {
        int arrLength = arr.length;
        List<Integer[]> arrList = new ArrayList<Integer[]>();
        int subarraysCount = (int) Math.ceil((double) arrLength
                / subArrSize);
        for (int i = 0; i < subarraysCount; i++) {
            if (i == subarraysCount - 1) {
                Integer[] curArr = Arrays.copyOfRange(arr, i * subArrSize,
                        arrLength);
                arrList.add(curArr);
            } else {
                Integer[] curArr = Arrays.copyOfRange(arr, i * subArrSize,
                        (i + 1) * subArrSize);
                arrList.add(curArr);
            }
        }
        return arrList;
    }
}

Related Tutorials