问题
I have the following Integer list
List<Integer> arrayList = new ArrayList<Integer>();
for (int i = 0; i < 7; i++) {
arrayList.add(i);
}
So the list is like this [0,1,2,3,4,5,6]. My scenario is
If I give the value = 5 as parameter then I would like to split 5 sub list like this
[0,5], [1,6] , [2], [3], [4]
If I give the value = 4 as parameter then I would like to split 4 sub list like this
[0,4], [1,5], [2,6] , [3]
If I give the value = 3 as parameter then I would like to split 3 sub list like this
[0,3,6], [1,4], [2,5]
I already tested with below function but it is not my need.
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;
}
At the above function, I give splitCount to 5
then the function returns
[0,1,2,3,4], [5,6]
The result I expect is [0,5], [1,6] , [2], [3], [4]
回答1:
How about:
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;
}
回答2:
Simple Solution Hope This Helps
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++;
}
}
回答3:
A functional implementation using Streams without variables:
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());
}
来源:https://stackoverflow.com/questions/45792207/fixed-sublist-count-but-dynamic-members-in-java