Split ArrayList into Multiple ArrayLists depending

2020-07-29 05:57发布

问题:

I have this program:

public static void main(String[] args){
    System.out.println("Enter number of nodes");
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    for(int i=0;i<=n;i++)
    {
        nodes.add(i);
    }

    System.out.println(nodes);
    System.out.println("How many subnetworks you want? Enter Small(10), Med(30), Large(50)");
    small = sc.nextInt();
    med = sc.nextInt();
    large = sc.nextInt();
    System.out.println("Small = " + small + "med" + med + "large" + large);

Now depending on value of small, medium and large and considering multiples of each of these integers, I want to split ArrayList into different arraylists or array. For example, small = 100, med = 50, large = 10 should split main arraylist into 100 small arraylists each of size 10, 50 med arraylists each of size 30 and 10 large arraylists each of size 50. After the split, I want to assign some properties to elements in sublsits. And I am not sure whether it should be arraylist or array or anything else.

回答1:

You can use split list function.

private static List<List<Integer>> splitAndReturn(List<Integer> numbers,
        int size) {
    List<List<Integer>> smallList = new ArrayList<List<Integer>>();
    int i = 0;
    while (i + size < numbers.size()) {
        smallList.add(numbers.subList(i, i + size));
        i = i + size;
    }
    smallList.add(numbers.subList(i, numbers.size()));
    return smallList;
}

The function will return an arrayList of arrays with each raw of size size. So if you need 100 array with size 10, then

splitAndReturn(yourList, 10).subList(0, 100);

will get you the list of arrays.



回答2:

Well the simple thing to do is to loop through the list and split them accordingly. Considering your example,

small = 100, med = 50, large = 10

first check if the list has enough values

if (list.size() >= ((small*10)+(med*30)+(large*50))){
    for (int i=0;i<small;i++){
        for(int j=0;j<10;j++){
            //copy array value
        }
    }    
    // do the same for med and large.
}