Search code examples
javaarraylistsublist

Add sublists to arraylist via for loop


How do I add the sublists I've made with a for loop to an ArrayList? Considering the number of sublists could potentially be hundreds, or even thousands. I know the code below is a no go, since the addAll need to have a list as a parameter, but it's the kinda thing I'm after.

List<Integer> list1 = arrayList.subList(0, 3);
List<Integer> list2 = arrayList.subList(3, 6);
List<Integer> list3 = arrayList.subList(6, 9);
ArrayList<Integer> newArray = new ArrayList<Integer>();
for (int i = 0; i < 3; i++) {
    String listNum = "list" + i;
    newArray.addAll(listNum);
}

Solution

  • You cannot "address" a local variable by index - you need an array for that:

    List<Integer>[] list = new List<Integer>[] {
        arrayList.subList(0, 3)
    ,   arrayList.subList(3, 6)
    ,   arrayList.subList(6, 9)
    };
    ArrayList<Integer> newArray = new ArrayList<Integer>();
    for (int i = 0; i < 3; i++) {
        newArray.addAll(list.get(i));
    }
    

    In your specific example you can construct sublist on the fly, without storing them in an array:

    ArrayList<Integer> newArray = new ArrayList<Integer>();
    for (int i = 0; i < 3; i++) {
        newArray.addAll(arrayList.subList(3*i, 3*(i+1)));
    }