Suppose if you have given an array list of size N and chunk size k < N, then divide the list into multiple sub lists where maximum sub list size is k.
For example, as you see above image, list has 15 elements and for the given chunk size 4, all the 15 elements are divided into 4 sub lists.
Following snippet takes a list and return sublists based on chunk size.
public static <T> List<List<T>> chunkedLists(List<T> list, final int chunkSize) {
if (list == null) {
throw new IllegalArgumentException("Input list must not be null");
}
if (chunkSize <= 0) {
throw new IllegalArgumentException("Chunk Size must be > 0");
}
List<List<T>> subLists = new ArrayList<List<T>>();
final int listSize = list.size();
for (int i = 0; i < listSize; i += chunkSize) {
subLists.add(new ArrayList<T>(list.subList(i, Math.min(listSize, i + chunkSize))));
}
return subLists;
}
Find the below working application.
ListUtil.java
package com.sample.app.utils;
import java.util.ArrayList;
import java.util.List;
public class ListUtil {
public static <T> List<List<T>> chunkedLists(List<T> list, final int chunkSize) {
if (list == null) {
throw new IllegalArgumentException("Input list must not be null");
}
if (chunkSize <= 0) {
throw new IllegalArgumentException("Chunk Size must be > 0");
}
List<List<T>> subLists = new ArrayList<List<T>>();
final int listSize = list.size();
for (int i = 0; i < listSize; i += chunkSize) {
subLists.add(new ArrayList<T>(list.subList(i, Math.min(listSize, i + chunkSize))));
}
return subLists;
}
}
ListUtilTest.java
package com.sample.app.utils;
import static com.sample.app.utils.ListUtil.chunkedLists;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class ListUtilTest {
@Test(expected = IllegalArgumentException.class)
public void nullCheck1() {
chunkedLists(null, 10);
}
@Test(expected = IllegalArgumentException.class)
public void negativeChunkSize() {
chunkedLists(Arrays.asList(2, 3, 4, 7), -1);
}
@Test
public void chunkTest() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
List<List<Integer>> subLists = chunkedLists(list, 4);
assertTrue(Arrays.asList(1, 2, 3, 4).equals(subLists.get(0)));
assertTrue(Arrays.asList(5, 6, 7, 8).equals(subLists.get(1)));
assertTrue(Arrays.asList(9, 10, 11, 12).equals(subLists.get(2)));
assertTrue(Arrays.asList(13, 14, 15).equals(subLists.get(3)));
}
}
You may
like
No comments:
Post a Comment