You could use commons lang's ArrayUtils.

array = ArrayUtils.removeElement(array, element)

commons.apache.org library:Javadocs

Answer from Peter Lawrey on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › remove-an-element-at-specific-index-from-an-array-in-java
Remove an Element at Specific Index from an Array in Java - GeeksforGeeks
July 11, 2025 - Explanation: This example includes finding the element at the specified index and then removing that element. The rest of the elements are copied into a new array. This would lead to an array of size one less than the original array. We can use Java 8 streams to remove element at specific index from an array, when modifying small or mid-sized arrays.
🌐
Reddit
reddit.com › r/learnprogramming › having trouble with java arrays, removing an element then returning a new size of an array
r/learnprogramming on Reddit: Having trouble with java arrays, removing an element then returning a new size of an array
July 13, 2018 -

So guys i'm having trouble finding a solution for this question. I'm kinda frustrated that i didn't solve this kind of problem during my exam for employment.

Problem: The task is to provide an implementation for the given function. int[] removeElem(int[] array, value), the objective is to find if the array contains the given 'value' inside it. if found then remove the element from the array then return an array with a new size, else return original array.

So far this is what i got:

  public static void main(String[] args) {
  int[] myArray = {5,6,9,4};
  
  int[] newArray = removeElem(myArray,9);
  
  for(int i=0;i<newArray.length;i++){
      System.out.print(newArray[i] + " ");
  }

}

public static int[] removeElem(int[] array, int value){
    int[] tempArray = array;
    int newArrayLength = 0;
    int[] newArray;
    
    for(int index=0;index < tempArray.length; index++){
        if(tempArray[index] == value){
            tempArray[index] = -1;
            newArrayLength++;
        }
    }
    
    newArray = new int[tempArray.length - newArrayLength];
    for(int index=0;index < newArray.length; index++){
        if(tempArray[index] != -1){
            newArray[index] = tempArray[index];
        }
    }
    
    return newArray;
    
}

Unfortunately i can't get it right :/

Edit: Thank you! everyone for suggesting different solutions to this problem, I feel like I need to work more on my solutions and such :|.

Top answer
1 of 5
2
I’m on my phone so I’ll just explain what im thinking in pseudo code, but why don’t you just do something like: Create a new array of size n-1 where n is the size of the original array. Iterate over the old array in a for loop, adding each element to the new array. If the element at the ith position equals the element to remove, continue to the next iteration. Would that work? EDIT: I'm at my PC now so here's the code. I ended up doing it a little differently than I mentioned above. Note that it doesn't account for if the element appears multiple times in the array or when the element does not exist. public static void main(String []args) { int[] myArray = { 5,6,9,4 }; int[] newArray = removeElem(myArray, 9); for (int i = 0; i < newArray.length; i++) System.out.print(newArray[i] + " "); } public static int[] removeElem(int[] array, int value) { int index = -1; // First confirm the element to remove exists in the array for (int i = 0; i < array.length; i++) { // If it does, store its index if (array[i] == value) index = i; } // If element exists if (index != -1) { int[] newArray = new int[array.length - 1]; for (int i = 0; i < array.length; i ++) { if (i < index) newArray[i] = array[i]; else if (i > index) newArray[i - 1] = array[i]; } return newArray; } // Do some error handling for if the element does not exist else return array; } Output is: 5 6 4
2 of 5
2
newArray[index] = tempArray[index]; This is your problem. As you skip elements that are to be removed, the insertion index in newArray must no longer match the read index in tempArray, but you're using the same index for both. You need to use two indices, and only increment the newArray index when you insert an element, while incrementing the tempArray index every time. Also the whole thing would be better if you just used Lists or Streams, but maybe your interviewer didn't want that. It's really best to try to avoid using raw arrays in Java.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-remove-array-elements
How to Remove Array Elements in Java | DigitalOcean
May 2, 2025 - Yes, you can remove an element from an array in Java. However, it’s important to note that arrays are fixed-size in Java, so you can’t directly remove elements from an array.
🌐
Software Testing Help
softwaretestinghelp.com › home › java › remove/delete an element from an array in java
Remove/Delete An Element From An Array In Java
April 1, 2025 - Using Java8 streams, we can delete an element from an array. In order to do this, first, the array is converted to a stream. Then the element at the specified index is deleted using the filter method of streams.
🌐
TutorialsPoint
tutorialspoint.com › home › java_data_structures › remove elements from array in java
Remove Elements from Array in Java
September 1, 2008 - Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Following is the algorithm to delete an element available at the Kth position of LA. Step 1 - Start Step 2 - Set J = K Step 3 - Repeat steps 4 and 5 while J < N Step 4 - Set LA[J] = LA[J + 1] Step 5 - Set J = J+1 Step 6 - Set N = N-1 Step 7 - Stop · public class RemovingElements { public static void main(String args[]) { int[] myArray = {10, 20, 30, 45, 96, 66}; int pos = 3; int j = myArray.length; for(int i = pos; i < j-1; i++) { myArray[i] = myArray[i+1]; } System.out.println("Contents of the array after deletion ::"); for(int i = 0; i < myArray.length-1; i++) { System.out.print(myArray[i]+ ", "); } } }
🌐
Baeldung
baeldung.com › home › java › java array › removing an element from an array in java
Removing an Element from an Array in Java | Baeldung
June 12, 2024 - Usually, this approach creates a brand-new array and copies all the values except for the value being removed. We can use the Apache Commons Lang library to remove the given element of an array.
🌐
W3Schools
w3schools.com › java › ref_arraylist_remove.asp
Java ArrayList remove() Method
Remove an integer from the list by position and by value: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(5); list.add(8); list.add(9); list.add(1); list.remove(Integer.valueOf(1)); // Remove by object list.remove(1); // Remove by index System.out.println(list); } }
🌐
Stack Abuse
stackabuse.com › remove-element-from-an-array-in-java
Remove Element from an Array in Java
December 16, 2021 - Here, we're simply iterating over the original array and copying elements from the original array into the new array, skipping the one we'd like to remove. ... In case you're already using the Apache Commons library, you can use the ArrayUtils.remove() method.
Find elsewhere
Top answer
1 of 16
116

[If you want some ready-to-use code, please scroll to my "Edit3" (after the cut). The rest is here for posterity.]

To flesh out Dustman's idea:

List<String> list = new ArrayList<String>(Arrays.asList(array));
list.removeAll(Arrays.asList("a"));
array = list.toArray(array);

Edit: I'm now using Arrays.asList instead of Collections.singleton: singleton is limited to one entry, whereas the asList approach allows you to add other strings to filter out later: Arrays.asList("a", "b", "c").

Edit2: The above approach retains the same array (so the array is still the same length); the element after the last is set to null. If you want a new array sized exactly as required, use this instead:

array = list.toArray(new String[0]);

Edit3: If you use this code on a frequent basis in the same class, you may wish to consider adding this to your class:

private static final String[] EMPTY_STRING_ARRAY = new String[0];

Then the function becomes:

List<String> list = new ArrayList<>();
Collections.addAll(list, array);
list.removeAll(Arrays.asList("a"));
array = list.toArray(EMPTY_STRING_ARRAY);

This will then stop littering your heap with useless empty string arrays that would otherwise be newed each time your function is called.

cynicalman's suggestion (see comments) will also help with the heap littering, and for fairness I should mention it:

array = list.toArray(new String[list.size()]);

I prefer my approach, because it may be easier to get the explicit size wrong (e.g., calling size() on the wrong list).

2 of 16
33

An alternative in Java 8:

String[] filteredArray = Arrays.stream(array)
    .filter(e -> !e.equals(foo)).toArray(String[]::new);
🌐
Netjstech
netjstech.com › 2017 › 07 › how-to-remove-elements-from-array-java.html
How to Remove Elements From an Array Java Program | Tech Tutorials
Enter Element to be deleted : 5 Elements -- 1 2 12 7 3 8 Enter Element to be deleted : 8 Elements -- 1 2 5 12 7 3 · With copying the element to the new array problem of empty space is solved. If you can use Apache commons in your application then there is a utility class ArrayUtils that can be used to remove elements from an array. import java.util.Scanner; import org.apache.commons.lang3.ArrayUtils; 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){ // Using ArrayUtils intArr = ArrayUtils.remove(intArr, i); break; } } System.out.println("Elements -- " ); for(int i = 0; i < intArr.length; i++){ System.out.print(" " + intArr[i]); } } }
🌐
How to do in Java
howtodoinjava.com › home › java array › removing items from an array in java
Removing Items from an Array in Java
February 10, 2022 - If the array doesn’t contains such an element, no elements are removed from the array. Let us look at a few examples of how to use these APIs. Java program to remove an item at index position 5. Integer[] originalArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; Integer[] reducedArray = ArrayUtils.remove(originalArray, 5); //[0, 1, 2, 3, 4, 6, 7, 8, 9]
🌐
Java67
java67.com › 2012 › 12 › how-to-remove-element-from-array-in-java-example.html
How to Remove an Element from Array in Java with Example | Java67
... There is no direct way to remove elements from an Array in Java. Though Array in Java objects, it doesn't provide any methods to add(), remove(), or search an element in Array.
🌐
Java Guides
javaguides.net › 2024 › 05 › java-remove-element-from-array.html
Java: Remove Element from Array
May 29, 2024 - This guide will cover different ways to remove an element from an array, including using loops, the System.arraycopy method, and converting the array to a list and back to an array. ... In Java, arrays are fixed-size data structures that store elements of the same type.
🌐
Quora
quora.com › How-does-one-remove-an-element-from-an-array-in-Java
How does one remove an element from an array in Java? - Quora
Answer (1 of 10): Removing an element from an array is a cumbersome effort if the order matters in your array. Otherwise, it is really easy. Let me explain both ways. Order of the elements does NOT matter Let’s assume your have a partially filled array [5, 9, 6, 8, 0, 0, 0] (0 means don’t ...
🌐
Codidact
software.codidact.com › posts › 289778
How do I remove an element from a Java array? - Software Development
One way to remove element from array is to replace element with zero. Below is a rough snippet I am sharing: ```java int N = sc.nextInt(); int pos...
🌐
Coderanch
coderanch.com › t › 454700 › java › Proper-remove-shift-elements-array
Proper way to remove and shift elements of an array (Beginning Java forum at Coderanch)
To "manipulate" an array especially removing elements and making no blanks... you need to use a (array) list (a form of collection). The idea of array list is that it represents the array "as a" list. ... K. Tsang CEng MBCS PMP PMI-ACP OCMJEA OCPJP ... You can try dissecting ArrayList and see how it does it In your Java™ installation folder there is a file called src.zip. Unzip that, and explore it (-->java-->util-->ArrayList). To delete an element from the middle of an array:
Top answer
1 of 3
6

The Java Collections framework is something that you should browse. There are also some types that aren't array-like (Set and Map) but you will find that you will use them often. There are many different types of collections, and some have advantages over others for certain types of operations.

Classic arrays

First, the thing that isn't in the collections framework. The Array. Not ArrayList, but rather the classic int[]. The advantage of the array is that it closely maps to what memory is. foo[42] is to lookup. Many system level calls that give you a fixed number of items are arrays and they are good to know. "1,2,3".split(",") returns back an array for example.

The problem with arrays is that they aren't that flexible. Adding an element to the end of an array that already is at is maximum capacity means allocating a new, larger array and then doing an System.arraycopy() (javadoc) to copy all the elements from one array to another array in a timely manner.

To remove an element from the list you need to remove it and then walk the remainder of the list to have everything be contagious again. If you want to remove foo[4] from the list, you then assign foo[4] = foo[5] and foo[5] = foo[6] and so on down to the end of the list. Thats if you have to do it by hand. You can also use that System.arraycopy mentioned to do it for you given the right set of arguments. Something like:

System.arraycopy(foo,5,foo,4,foo.length - 4);

I might have that wrong, but thats the general idea. Copying the array back on itself. It should work.

If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.

Lists

As you see, arrays are a bit awkward to work with. You've got do it all by hand. Its good to know, but a pain to practice. There are two lists that are in common use that make this easier for you. For the most part, Lists look like arrays.

List<Integer> foo = ...;
foo.get(4);
foo.remove(5);

You call methods on them, but you are fetching the 4th element via method call instead of via direct access through the array. See that foo.remove(5). Thats it. You're done. You have removed an element from the list and deleted it. Much easier to remember.

ArrayList

The ArrayList is backed by an Array. This means that doing foo.get(4) runs fast, but foo.add(42, foo.size()+1) is likely to be slow because it has to do all of that moving of things around to allocate a new list (yes, I know that the list can be longer than the size, but lets assume that its the same size as its actual list).

Instead of having to remember how to do all the shuffling, you've got nice methods to do your work for you. It doesn't mean that its not done (the work is still done behind the scenes of the interface), but its something that you don't have to worry about.

So, the ArrayList is for:

  • fast get (O(1))
  • slow remove and insert (O(length))
  • slow append when full (O(length))

LinkedList

For some reason, everyone's goto list implementation is the ArrayList. I don't know why. Many times when I'm working with Lists, the LinkedList is the one that is more applicable. You keep adding things to the end. Rarely do you want the nth element. You just want to iterate over them.

This is what the LinkedList is good for. It does fast remove and append and its iterator is just as fast as the ArrayList. Its just if you want foo.get(400) its going to be a bit slower than the ArrayList implement.

The LinkedList is also a Deque too, but people forget about that. That lets you access the LinkedList as a double ended queue (nice for implementing a Stack or Queue).

So, if you are just appending and iterating, the LinkedList is for you.

  • Get is slowish (O(index))
  • Fast append (O(1))
  • Remove and insert is slowish (O(index))

Note that the O(index) there is a bit of an award bit. It will index depending on which way is faster to get there (from the end or start). So if the LinkedList is 100 long, and you get(10), it starts from the start. If you ask for get(90), it starts from the end. So get(index) is never more than get(length/2), but thats all just factors that don't matter when looking at Big O.

2 of 3
1

If you must really do this using an array, then you will need to:

  • copy all elements of the array after the element being deleted down by one position to cover the removed element.

  • resize your array to be smaller by one element.

Copying elements down by one position can be done either by writing a loop yourself, or by invoking System.arraycopy( src, srcPos, dest, destPos, length).

Resizing the array can be done like this: myArray = Arrays.copyOf( myArray, newCapacity ).

That having been said, if you have any need to manipulate the length of the array, then definitely go with ArrayList instead of using arrays. This wheel has already been invented.