[英]Adding chunks of array into array list in java
我想將一個數組(具有隨機整數值)分成相等大小的較小塊,並根據基於數組的值分配元素。 例如,如果我有一個大小為9的數組,並想將其分為3個塊,則將0和3之間的數字分配給第一個塊,將4-6之間的數字分配給第二個塊,其余分配給第三個塊。 我必須遍歷單獨的塊(可以暫時保留)。 最后將所有塊添加到數組列表中。
int[] originalarray = init[9];
int number = original.length/numerToDivede;
Arraylist<int[]> bigarray = new Arraylist<>();
int[] array1= null;
int[] array2;
int[] array3;
for(int i=0;i<originalarrays.length-1;i++){
if(originalArrays[i] < numberTodivide){
// add to the first array1;
}else if (originalArrays[i] < 2*numberTodivide){
// add to the second array
}else
// add to the third array
這是我所采用的方法,但是每件事都是硬編碼的。 我動態地做到了嗎? 感謝您的幫助!
希望這個能對您有所幫助
List<Integer> bigarray = new ArrayList<>();
bigarray.addAll(Arrays.asList(1,2,3,4,1,2,3,33,3,4,1,2,1));
List<List<Integer>> outputList = new ArrayList<>();
while(!bigarray.isEmpty()){
List<Integer> tmpList = bigarray.stream()
.filter(item -> item == bigarray.get(0))
.collect(Collectors.toList());
//filter all item has been collect this time
List<Integer> filter = bigarray.stream().filter(item -> item != bigarray.get(0)).collect(Collectors.toList());
bigarray.clear();
bigarray.addAll(filter);
// add the result in this time
outputList.add(tmpList);
}
outputList.forEach(list -> list.forEach(item -> System.out.print(item+", ")));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.