我有一个整数集合(这可以是动态数据源)
ArrayList<Int> data = [1,2,3,4,5,6,7]
我能做什么
我可以使用 here 的答案生成 Equal 数据集,例如 [1,2,3][4,5,6] [7]
问题:我如何限制组的数量(例如最大 2),以便结果输出为
[1,2,3,4][5,6,7]
或[1,2,3][4,5,6,7]
最佳答案
您可以迭代列表,将项目分为子组,直到达到限制,然后将其余元素添加到最后一个组,而不是使用第三方库
private static List<List<Integer>> partition(List<Integer> list, int groupSize, int limit) {
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
int groupIndex = i / groupSize;
if(groupIndex > limit - 1) {
groupIndex = limit - 1;
}
if(groupIndex >= result.size()) {
result.add(new ArrayList<>());
}
result.get(groupIndex).add(list.get(i));
}
return result;
}
关于java - java中集合的分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60589491/