Skip to content

Instantly share code, notes, and snippets.

@kirill578
Created January 4, 2017 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirill578/a6077cd603ab5c79bdd817ddd832c3a7 to your computer and use it in GitHub Desktop.
Save kirill578/a6077cd603ab5c79bdd817ddd832c3a7 to your computer and use it in GitHub Desktop.
public class ListUtils {
/**
* Partitions lists into batches of minimum and maximum size.
* examples when min=2, max=4:
* [1, 2, 3, 4 ,5] -> [[1, 2, 3], [4, 5]]
* [1, 2, 3, 4] -> [[1, 2, 3, 4]]
* [1, 2, 3, 4, 5 ,6] -> [[1, 2, 3, 4] [5, 6]]
* @param originalList - list to parition
* @param max - maximum size of sublist
* @param min - minimum size of sublist
* @return
*/
public static <T> List<List<T>> partition(List<T> originalList, int max, int min) {
if (originalList.size() < min) {
throw new IllegalArgumentException("list size is smaller than the minimum");
}
List<List<T>> partitioned = new ArrayList<>(Lists.partition(originalList, max));
if (partitioned.size() >= 2) {
int lastIndex = partitioned.size() - 1;
int beforeLastIndex = partitioned.size() - 2;
LinkedList<T> lastList = new LinkedList<>(partitioned.get(lastIndex));
LinkedList<T> beforeLastList = new LinkedList<>(partitioned.get(beforeLastIndex));
while (lastList.size() < min) {
lastList.addFirst(beforeLastList.removeLast());
}
partitioned.set(lastIndex, lastList);
partitioned.set(beforeLastIndex, beforeLastList);
}
return partitioned;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment