Chunk list function

As far as I know I haven’t seen in the apache commons library a function which allows you to divide a list into several lists. There is a function in Guava which does exaclty this but for those who don’t want to add another dependency to their projects can use the following function. This util is based in the Java function subList.

	public static <T> List<List<T>> chunk(List<T> list, int number) {
		assert number > 0;
		List<List<T>> result = new ArrayList<List<T>>();
		int start = 0;
		while (start < list.size()) {
			int offset = Math.min(list.size() - start, number);
			result.add(list.subList(start, start = start + offset));
		}
		return result;
	}

Here we’ve got the JUnit which checks that everything is working as expected:

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class BatchTest {

	@Test
	public void testChunk1() {
		String[] list = {"a", "b"};
		List<List<String>> chunkList = CollectionUtils.chunk(Arrays.asList(list), 3);
		print("Test 1:", chunkList);
		assertEquals(chunkList.size(), 1);
	}

	@Test
	public void testChunk2() {
		String[] list = {"a", "b", "c", "d", "e", "f", "g", "h"};
		List<List<String>> chunkList = CollectionUtils.chunk(Arrays.asList(list), 3);
		print("Test 2:", chunkList);
		assertEquals(chunkList.size(), 3);
	}

	@Test
	public void testChunk3() {
		String[] list = {};
		List<List<String>> chunkList = CollectionUtils.chunk(Arrays.asList(list), 2);
		print("Test 3:", chunkList);
		assertEquals(chunkList.size(), 0);
	}

	private void print(String literal, List<List<String>> chunkList) {
		System.out.println(literal);
		for (List<String> chunk : chunkList) {
			for (String string : chunk) {
				System.out.print(string + ",");
			}
			System.out.println();
		}
	}
}

And here is the result:

Test 1:
a,b,
Test 2:
a,b,c,
d,e,f,
g,h,
Test 3:
Tagged on: ,

Leave a Reply

Your email address will not be published. Required fields are marked *


+ 7 = eight

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>