根据用户输入将 ArrayList 拆分为多个 ArrayList [英] Split ArrayList into Multiple ArrayLists depending on user input
问题描述
我有这个程序:
public static void main(String[] args){
System.out.println("Enter number of nodes");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=0;i<=n;i++)
{
nodes.add(i);
}
System.out.println(nodes);
System.out.println("How many subnetworks you want? Enter Small(10), Med(30), Large(50)");
small = sc.nextInt();
med = sc.nextInt();
large = sc.nextInt();
System.out.println("Small = " + small + "med" + med + "large" + large);
现在根据 small、medium 和 large 的值并考虑每个整数的倍数,我想将 ArrayList 拆分为不同的数组列表或数组.例如,small = 100, med = 50, large = 10 应该将主数组列表拆分为 100 个大小为 10 的小数组列表、50 个大小为 30 的 med 数组列表和 10 个大小为 50 的大数组列表.拆分后,我想为 sublsits 中的元素分配一些属性.而且我不确定它是否应该是 arraylist 或 array 或其他任何东西.
Now depending on value of small, medium and large and considering multiples of each of these integers, I want to split ArrayList into different arraylists or array. For example, small = 100, med = 50, large = 10 should split main arraylist into 100 small arraylists each of size 10, 50 med arraylists each of size 30 and 10 large arraylists each of size 50. After the split, I want to assign some properties to elements in sublsits. And I am not sure whether it should be arraylist or array or anything else.
推荐答案
可以使用拆分列表功能.
You can use split list function.
private static List<List<Integer>> splitAndReturn(List<Integer> numbers,
int size) {
List<List<Integer>> smallList = new ArrayList<List<Integer>>();
int i = 0;
while (i + size < numbers.size()) {
smallList.add(numbers.subList(i, i + size));
i = i + size;
}
smallList.add(numbers.subList(i, numbers.size()));
return smallList;
}
该函数将返回一个数组的arrayList,每个原始大小为size
.因此,如果您需要 100 个大小为 10 的数组,则
The function will return an arrayList of arrays with each raw of size size
.
So if you need 100 array with size 10, then
splitAndReturn(yourList, 10).subList(0, 100);
会给你数组列表.
这篇关于根据用户输入将 ArrayList 拆分为多个 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!