I have an ArrayList, which I want to divide into smaller Lists of n size, and perform an operation on each. My current method of doing this is
implemented with Array
Well i wrote one myself before i saw ColinD's answer (+1) and using Guava is definitely the way to go. It was too much fun to leave alone and so the below gives you a copy of the list rather than views so GUava's is definitely more efficient than this. I'm posting this because it was fun to write rather than suggesting it is as efficient:
The Hamcrest test (one of anyway):
assertThat(chunk(asList("a", "b", "c", "d", "e"), 2),
equalTo(asList(asList("a", "b"), asList("c", "d"), asList("e"))));
The code:
public static Iterable> chunk(Iterable in, int size) {
List> lists = new ArrayList();
Iterator i = in.iterator();
while (i.hasNext()) {
List list = new ArrayList();
for (int j=0; i.hasNext() && j