Skip to content

Instantly share code, notes, and snippets.

@kencoba
Created May 5, 2017 05:28
Show Gist options
  • Save kencoba/5e41f0005773fa4f26963dd45ea443a8 to your computer and use it in GitHub Desktop.
Save kencoba/5e41f0005773fa4f26963dd45ea443a8 to your computer and use it in GitHub Desktop.
A partition method.
import java.util.ArrayList;
import java.util.List;
public class ListUtils {
public static <T> List<List<T>> partition(
List<T> list,
int size) {
if (list == null) { throw new NullPointerException("List must not be null.");}
if (size <= 0) { throw new IllegalArgumentException("Size must be greater than 0.");}
List<List<T>> result = new ArrayList<List<T>>();
for (int start = 0 ; start < list.size();start += size) {
int end = (start + size) < list.size() ? (start + size) : (start + (list.size() % size));
result.add(list.subList(start, end));
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment