I have a list of random size greater than 20k. How can I split them into sublists where each sublist will have equal lengths or equal length + 1(for the odd lists?)?
Since it is random size, implementation should not have any defined size right?
I am currently looking at this template:
public static <T> List<List<T>> split(List<T> list, int size) throws NullPointerException, IllegalArgumentException {
if (list == null) {
throw new NullPointerException("The list parameter is null.");
}
if (size <= 0) {
throw new IllegalArgumentException("The size parameter must be more than 0.");
}
int num = list.size() / size;
int mod = list.size() % size;
List<List<T>> ret = new ArrayList<List<T>>(mod > 0 ? num + 1 : num);
for (int i = 0; i < num; i++) {
ret.add(list.subList(i * size, (i + 1) * size));
}
if (mod > 0) {
ret.add(list.subList(num * size, list.size()));
}
return ret;
}
This one is creating sublists based on known sublist size then creating the X sublists.
The result I need is to pass a LIST and a target sublistSize. So I pass a list with size 26346 records and sublistSize 5. I would end up with 5 sublists. the first four sublist would have 5269 records, and the last(5th) sublist would have 5270 records.
How about this? This will do what you said (if the order of the items is not important), create 'size' sublists, and it will distribute all items to the new lists.
public static <T> List<List<T>> split(List<T> list, int size)
throws NullPointerException, IllegalArgumentException {
if (list == null) {
throw new NullPointerException("The list parameter is null.");
}
if (size <= 0) {
throw new IllegalArgumentException(
"The size parameter must be more than 0.");
}
List<List<T>> result = new ArrayList<List<T>>(size);
for (int i = 0; i < size; i++) {
result.add(new ArrayList<T>());
}
int index = 0;
for (T t : list) {
result.get(index).add(t);
index = (index + 1) % size;
}
return result;
}