'Generate N number of Sublists from a List in Java

I have working with Java lists I want to generates sublist simply says how to partioning of list into N parts:

    arr= new int [10];
    for (int i = 1; i < arr.length; i++) {
        arr[i] = i;
    }
Input:
arr=[1,2,3,4,5,6,7,8,9] // is not always sorted list
S= 3 // if S=3 create 3 sublists //if S=4 create 4 sublists so on..

output is :
sublist1=[1,2,3] sublist2=[4,5,6] sublist3=[7,8,9]

How to acheive this type of Result in Java



Solution 1:[1]

You can use this method for splitting any Java collection (e.g. lists) into multiple lists:

public static <T extends Object> List<List<T>> split(List<T> list,
                                                     int targetSize) {
    List<List<T>> lists = new ArrayList<List<T>>();
    for (int i = 0; i < list.size(); i += targetSize) {
        lists.add(list.subList(i, Math.min(i + targetSize, list.size())));
    }
    return lists;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 stepanian