我有以下整数列表
List<Integer> arrayList = new ArrayList<Integer>();
for (int i = 0; i < 7; i++) {
arrayList.add(i);
}
Run Code Online (Sandbox Code Playgroud)
所以列表就像这样[0,1,2,3,4,5,6].我的情景是
如果我给value = 5作为参数,那么我想像这样拆分5个子列表
[0,5], [1,6] , [2], [3], [4]
Run Code Online (Sandbox Code Playgroud)
如果我给value = 4作为参数,那么我想像这样拆分4个子列表
[0,4], [1,5], [2,6] , [3]
Run Code Online (Sandbox Code Playgroud)
如果我给value = 3作为参数,那么我想像这样拆分3个子列表
[0,3,6], [1,4], [2,5]
Run Code Online (Sandbox Code Playgroud)
我已经测试了以下功能,但这不是我的需要.
public List<List<Integer>> chopped(List<Integer> list, final int splitCount) {
List<List<Integer>> parts = new ArrayList<List<Integer>>();
final int N = list.size();
for (int i = 0; i < N; i += splitCount) {
parts.add(new ArrayList<Notification>(list.subList(i, Math.min(N, i + splitCount))));
}
return parts;
}
Run Code Online (Sandbox Code Playgroud)
在上面的函数中,我给splitCount 5然后函数返回
[0,1,2,3,4], [5,6]
Run Code Online (Sandbox Code Playgroud)
我期望的结果是 [0,5], [1,6] , [2], [3], [4]
怎么样:
public List<List<Integer>> chopped(List<Integer> list, final int splitCount) {
List<List<Integer>> parts = new ArrayList<>(splitCount);
for (int i = 0; i < splitCount; ++i) {
parts.add(new ArrayList<>());
}
final int N = list.size();
for (int i = 0; i < N; ++i) {
parts.get(i % splitCount).add(list.get(i));
}
return parts;
}
Run Code Online (Sandbox Code Playgroud)