我有一个大于20k的随机大小列表.如何将它们拆分为子列表,其中每个子列表将具有相等的长度或相等的长度+ 1(对于奇数列表?)?
由于它是随机大小,实现不应该有任何定义的大小吗?
我目前正在查看此模板:
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;
}
Run Code Online (Sandbox Code Playgroud)
这个是基于已知的子列表大小创建子列表,然后创建X子列表.
我需要的结果是传递LIST和目标sublistSize.所以我传递了一个大小为26346条记录和sublistSize 5的列表.我最终会得到5个子列表.前四个子列表将有5269个记录,最后一个(第五个)子列表将有5270个记录.
这个怎么样?这将按照您的说法执行(如果项目的顺序不重要),创建"大小"子列表,它会将所有项目分发到新列表.
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7452 次 |
| 最近记录: |