Created
January 4, 2017 09:05
-
-
Save kirill578/a6077cd603ab5c79bdd817ddd832c3a7 to your computer and use it in GitHub Desktop.
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
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