Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 608
user3628503 Avatar asked Dec 18 '25 05:12

user3628503


1 Answers

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)));
}
like image 166
Sergey Kalinichenko Avatar answered Dec 19 '25 23:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!