Created
January 3, 2014 23:07
-
-
Save bmchild/8248461 to your computer and use it in GitHub Desktop.
Splitting a list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* creates a list of lists where each list.size() <= <code>length</code> | |
* @param list | |
* @param length | |
* @return | |
*/ | |
public static <T> List<List<T>> split(List<T> list, final int length) { | |
List<List<T>> parts = new ArrayList<List<T>>(); | |
final int size = list.size(); | |
for (int i = 0; i < size; i += length) { | |
parts.add(new ArrayList<T>( | |
list.subList(i, Math.min(size, i + length))) | |
); | |
} | |
return parts; | |
} | |
//and the tests below | |
@Test | |
public void testSplit() throws Exception { | |
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); | |
List<List<Integer>> splits = CollectionUtil.split(nums, 2); | |
assertEquals(6, splits.size()); | |
assertEquals(1, splits.get(5).size()); | |
} | |
@Test | |
public void testSplit_NOSPLIT() throws Exception { | |
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6); | |
List<List<Integer>> splits = CollectionUtil.split(nums, 10); | |
assertEquals(1, splits.size()); | |
assertEquals(nums.size(), splits.get(0).size()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment