# Split a Map into sublists

I may get a Map of many many items that needs to be requested to an API.

In order to improve performance, I thought about splitting that list into smaller sublists, and querying the API with this small subset.

For that, I came to this code and was wondering what was your opinion on it.

This is some banal initiator I used to test my code:

Map<String, Integer> map = new LinkedHashMap<String, Integer>();
for (int i = 0; i < 550;i ++) {
map.put(String.valueOf(i), i);
}


Now the real code:

    int length = 100;
int pages = (int) Math.ceil((double) items.size() / length);

for (int i = 0; i < pages; i++) {
List<Integer> sub = items.subList(i * length, ((i+1) * length > items.size() ? items.size() : (i+1) * length));
System.out.println(sub.get(0));
System.out.println(sub.get(sub.size() - 1));
System.out.println("--");

// In my case, I would call the API here, at that place, using the sublist
}


The final output is:

0
99
--
100
199
--
200
299
--
300
399
--
400
499
--
500
549
--


This works great. What's your opinion on it?

• Can you describe the problem domain and what the code does a little better? This question was flagged as Unclear and I tend to agree with that assessment. – RubberDuck Dec 22 '14 at 13:44

The implementation is simple enough to require any comments. Just a few things:

• Is LinkedList a requirement? Can't it be done by an ArrayList?
• Use Math.min while making the subList.

An alternative for simpler solution You can add the Guava library to your project and use the Lists.partition method, e.g.

List<Integer> items = ...
List<List<Integer>> subLists= Lists.partition(items, pageSize);


Ok I've found a better alternative from the StackOverflow website :

public static <T> ArrayList<T[]> chunks(ArrayList<T> bigList,int n){
ArrayList<T[]> chunks = new ArrayList<T[]>();

for (int i = 0; i < bigList.size(); i += n) {
T[] chunk = (T[])bigList.subList(i, Math.min(bigList.size(), i + n)).toArray();
}

return chunks;
}


I believe it's better because :

• There is less code
• Less calculs (ceil)
• Less looping size (not from 1 to size(), but up to size() by length jumps)