0
\$\begingroup\$

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;
    List<Integer> items = new LinkedList<Integer>(map.values());
    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?

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – RubberDuck Dec 22 '14 at 13:44
2
\$\begingroup\$

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);
\$\endgroup\$
0
\$\begingroup\$

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();         
        chunks.add(chunk);
    }

    return chunks;
}

(source: https://stackoverflow.com/a/21233731/330867)

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)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.