What\'s the simplest, most standard, and/or most efficient way to split a List into two sub-Lists in Java? It\'s OK to mutate the original List, so no copying should be nece
Likewise cribbing off of Marc's list, we'll use List.removeAll() to remove the duplicate entries from the second list. Note that, strictly speaking, this only follows the specs if the original list contained no duplicate items: otherwise, the original list may be missing items.
<T> List<T> split(List<T> list, int i) {
List<T> x = new ArrayList<T>(list.subList(i, list.size()));
// Remove items from end of original list
list.removeAll(x);
return x;
}
A generic function to split a list to a list of list of specific size. I was missing this for long in java collections.
private List<List<T>> splitList(List<T> list, int maxListSize) {
List<List<T>> splittedList = new ArrayList<List<T>>();
int itemsRemaining = list.size();
int start = 0;
while (itemsRemaining != 0) {
int end = itemsRemaining >= maxListSize ? (start + maxListSize) : itemsRemaining;
splittedList.add(list.subList(start, end));
int sizeOfFinalList = end - start;
itemsRemaining = itemsRemaining - sizeOfFinalList;
start = start + sizeOfFinalList;
}
return splittedList;
}