remove element from array java code example

Example 1: how to delete an element from an array in java

import java.util.Scanner;

public class ElemRemoval {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] intArr = {1, 2, 5, 12, 7, 3, 8};
        System.out.print("Enter Element to be deleted : ");
        int elem = in.nextInt();
        
        for(int i = 0; i < intArr.length; i++){
            if(intArr[i] == elem){
                // shifting elements
                for(int j = i; j < intArr.length - 1; j++){
                    intArr[j] = intArr[j+1];
                }
                break;
            }
        }
      
        System.out.println("Elements -- " );
        for(int i = 0; i < intArr.length - 1; i++){
            System.out.print(" " + intArr[i]);
        }                
    }
}

Example 2: java array delete elements

//Make an res array that is equal to a but don't contains number 0
int[] res = Arrays.stream(a).filter(x -> x != 0).toArray();

Example 3: remove element from array java

Use ArrayList XD
import java.util.ArrayList;
array.remove(i); //remove element by index

Example 4: deleting elements of an array in java

import java.util.Scanner;

public class ElemRemoval {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] intArr = {1, 2, 5, 12, 7, 3, 8};
        System.out.print("Enter Element to be deleted : ");
        int elem = in.nextInt();
        
        for(int i = 0; i < intArr.length; i++){
            if(intArr[i] == elem){
                // shifting elements
                for(int j = i; j < intArr.length - 1; j++){
                    intArr[j] = intArr[j+1];
                }
                break;
            }
        }
      
        System.out.println("Elements -- " );
        for(int i = 0; i < intArr.length; i++){
            System.out.print(" " + intArr[i]);
        }                
    }
}

Example 5: hhow to remove elements from java

how to remove elements from java

Tags: