我有以下整数列表
List<Integer> arrayList = new ArrayList<Integer>();
for (int i = 0; i < 7; i++) {
arrayList.add(i);
}
所以列表就像这样[0,1,2,3,4,5,6]。我的方案是
如果我将value = 5作为参数,那么我想像这样分割5个子列表
[0,5], [1,6] , [2], [3], [4]
如果我将value = 4作为参数,那么我想像这样分割4个子列表
[0,4], [1,5], [2,6] , [3]
如果我给出value = 3作为参数,那么我想像这样分割3个子列表
[0,3,6], [1,4], [2,5]
我已经使用以下功能进行了测试,但这不是我的需要。
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;
}
在上面的函数中,我将splitCount赋予5
,然后函数返回
[0,1,2,3,4], [5,6]
我期望的结果是[0,5], [1,6] , [2], [3], [4]
答案 0 :(得分:6)
怎么样:
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;
}
答案 1 :(得分:0)
使用没有变量的Streams的功能实现:
public static void main(String[] args) {
List<Integer> asList = Arrays.asList(0, 1, 2, 3, 4, 5, 6);
System.out.println(chopped(asList, 3));
}
private static List<List<Integer>> chopped(List<Integer> source, int splitCount) {
return IntStream.range(0, splitCount)
.boxed()
.map(index -> getElements(source, index, splitCount))
.collect(Collectors.toList());
}
private static List<Integer> getElements(List<Integer> source, int index, int splitCount) {
return IntStream.range(0, source.size())
.filter(i -> i % splitCount == index)
.map(i -> source.get(i))
.boxed()
.collect(Collectors.toList());
}
答案 2 :(得分:0)
ArrayList<Integer> al1 = new ArrayList<>();
ArrayList<ArrayList<Integer>> al2 = new ArrayList<>();
// Add objects in al1 ...
int numberToSplit = 2;
if (numberToSplit > al1.size()) {
throw new Exception("Your message");
} else {
ArrayList<Integer> newArr;
int counter = 0;
for (int j = 0; j < numberToSplit; j++) {
newArr = new ArrayList<>();
for (int k = counter; k < al1.size(); k = k + numberToSplit) {
newArr.add(ALI.get(k));
}
al2.add(newArr);
counter++;
}
}