[英]Split ArrayList into Multiple ArrayLists depending on user input
I have this program: 我有这个程序:
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);
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. 现在取决于小,中,大的值并考虑每个整数的倍数,我想将ArrayList拆分成不同的arraylists或数组。 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.
例如,小= 100,med = 50,大= 10应该将主要的arraylist分成100个小的arraylists,每个大小为10,50个med arraylists,每个大小为30和10个大型arraylists,每个大小为50.分裂后,我想为sublsits中的元素指定一些属性。 And I am not sure whether it should be arraylist or array or anything else.
而且我不确定它是否应该是arraylist或array或其他任何东西。
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;
}
The function will return an arrayList of arrays with each raw of size size
. 该函数将返回阵列的ArrayList与大小的每个的原始
size
。 So if you need 100 array with size 10, then 因此,如果您需要100个大小为10的数组,那么
splitAndReturn(yourList, 10).subList(0, 100);
will get you the list of arrays. 会得到你的阵列列表。
Well the simple thing to do is to loop through the list and split them accordingly. 那么简单的事情是遍历列表并相应地拆分它们。 Considering your example,
考虑你的例子,
small = 100, med = 50, large = 10
小= 100,med = 50,大= 10
first check if the list has enough values 首先检查列表是否有足够的值
if (list.size() >= ((small*10)+(med*30)+(large*50))){
for (int i=0;i<small;i++){
for(int j=0;j<10;j++){
//copy array value
}
}
// do the same for med and large.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.