1

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.

4
  • 1
    Well, assume you have 6 items in the ids list and max is 3. Then when you get to i=4, you're trying to get items 4 through 7. But the list only has items 0 through 5. Commented Apr 27, 2017 at 8:31
  • @RealSkeptic Yes I get it now , when i + max is more than ids size , the toIndex should be set to ids size. thanks Commented Apr 27, 2017 at 8:35
  • 1
    @RealSkeptic i can never be 4 because it is always a multiple of 3 in your example. But if he has 7 or 8 items, he will get the exception when i=6. -> @ Hmahwish ever tried to use a debugger? Commented Apr 27, 2017 at 8:36
  • @DanielAlder I understood my logical error here .Thanks Commented Apr 27, 2017 at 8:38

2 Answers 2

2

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()); } 
Sign up to request clarification or add additional context in comments.

1 Comment

I got the logical error now , to set the to index size to ids.size if its less than max. Thanks
1
List<String> chunk = ids.subList(i, i + max); 

what is max? i + max should not be greater than ids.size()

1 Comment

@Daniel Alder Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.