Reputation: 2232
I have to divide a list of string in chunks ,hence I have written this method ,
public static List<List<String>> chunkIds(List<String> ids,
int max) {
List<List<String>> chunks = new ArrayList<>();
for (int i = 0; i < ids.size(); i = i + max) {
List<String> chunk = ids.subList(i, i + max);
chunks.add(chunk);
}
return chunks;
}
when I call the method I get IndexOutOfBoundsException on getting the subList .where max is a chunk size .Could someone please help me understand the index logic wrong here.
Upvotes: 1
Views: 101
Reputation: 117
List<String> chunk = ids.subList(i, i + max);
what is max
? i + max
should not be greater than ids.size()
Upvotes: 1
Reputation: 140544
If you use i + max
as the second parameter to subList
, if ids.size()
isn't exactly divisible by max
, that index will be greater than ids.size()
.
Use
Math.min(i + max, ids.size())
instead of i + max
.
Or, avoiding calculating the min
each time:
int i;
for (i = 0; i + max < ids.size(); i += max) {
chunks.add(ids.subList(i, i + max));
}
if (i < ids.size()) {
chunks.add(ids.subList(i, ids.size());
}
Upvotes: 2