简体   繁体   中英

Remove redundant from the array

int[] arr1 = {5,122,1,44,1,6,4,1,33,1,89,1,225,162,1,1,1,75,11,1,1,1}; 
int remove = 1;

for(int i = 0; i < arr1.length ; i++) { 
    if(remove == arr1[i]) {
        for(int j = i; j <arr1.length - 1; j++) {
            arr1[j] = arr1[j+1];
        }
        break;                                                  
    }
}
for(int i = 0; i<arr1.length-1; i++) {
       System.out.print(arr1[i] + " ");
       }
}

}

I wanna remove number 1 from this array? It won't be worked why?! But aftter changing the number one to any number from the array it will be removed! BUT why I can't remove the Number 1 ? From this array?

There are various (and efficient) ways to do this. but staying strictly to your code and use of array I would suggest something like this.

First go ahead and count the number of occurences, then create another array where you will store the rest of the numbers.

Then have another loop where you iterate through the first array, and if it doesn't match the number you are trying to remove, simply add it to the new array.

int[] arr1 = {5,122,1,44,1,6,4,1,33,1,89,1,225,162,1,1,1,75,11,1,1,1};
    int remove = 1;

    int occurences =0, counter=0;

    for(int i = 0; i < arr1.length ; i++) {
        if(remove == arr1[i]) {
            occurences++;
        }
    }

   int[] subArray = new int[arr1.length - occurences];

    //now recreate this

    for(int i = 0; i < arr1.length ; i++) {
        if(remove != arr1[i]) {
           subArray[counter++] = arr1[i];
        }
    }

    for(int i=0; i< subArray.length; i++){
        System.out.print(subArray[i] + " ");
    }

Samip has already provided something that is clear and works, but in case anyone is curious about an alternate solution, we can also use Streams API.

import java.util.Arrays;
import java.util.stream.Collectors;

public class RemoveOne {

    public static void main(String[] args) {
    int[] arr1 = { 5, 122, 1, 44, 1, 6, 4, 1, 33, 1, 89, 1, 225, 162, 1, 1, 1, 75, 11, 1, 1, 1 };
    int remove = 1;

    int[] removedArr = Arrays.stream(arr1)
                             .filter(number -> (number != remove))
                             .toArray();

    Arrays.stream(removedArr)
          .forEach(element -> System.out.print(element + " "));

    }

}

Output: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM