How to remove a value from array in Java

Posted by Somesh Shinde On Sunday, 26 June 2016 0 comments

How to remove a value from array in Java


In the last article, I have showed you how to reverse an array in place in Java and now I have come back with another array based coding interview question. It's also one of the frequently asked coding questions, not as popular as the previous one but still has been asked lot of times. Let's see the problem statement first.

Problem: Given an array and a value, write a function to remove all instances of that value from the array in Java (in place) and return the new length, or simply print out the array before and after removing the number. The order of elements can be changed. It doesn't matter what you leave beyond the new length. For example, if the given array is {12, 122, 12, 13, 14, 23, 14}, and number to be removed is 12 then the result array should be {122, 13, 34, 23,14}, and the length of the new array is 5.



How to remove a value from array in Java

In this article, I am going to show you two ways to remove a number from an integer array in Java. Our first solution will use the LinkedList class of Java Collection framework and the second solution will do it without using collection framework, as per the algorithm described below.

Solution 1:
In this solution, I have used a LinkedList class to collect all non-matching elements. So, I scan through original array and keep adding elements which are not equal to target value into LinkedList. Once I have completed the scan, I have all the numbers without target value in LinkedList. Later I use the Apache Commons ArrayUtils class to convert this LinkedList into an array in Java. There you go, you have removed the target number from the array without a fuss.

The only problem with this approach is that you need an extra LinkedList to hold rest of values and you now have your code dependent on Apache commons library

Solution 2:
The most straightforward way to remove a value from an array is to loop through the whole array, from the beginning to end. When the target value (number) is found, remove it and move all numbers behind it backward. The overall complexity of this algorithm is quadratic i.e. O(n^2) since we have to move O(n) numbers when a target number is removed.

2 ways to remove an element from array in Java


Java Program to remove an element from array

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

/**
 * Sample Program to show how to remove elements from array in Java.
 * In this program, we have used two ways, first by using LinkedList  * class of Java Collection framework and second without using Collection framework. *
 * @author javinpaul
 */
public class RemoveNumberFromArray {

    public static void main(String args[]) {

        System.out.println("Test #1 : General case to remove number  22");
        int[] input = {42, 322, 22, 11, 22, 33, 16};
        System.out.println("input : " + Arrays.toString(input) + ", remove 22");
        int[] output = remove(input, 22); // removes number 22 from array
        System.out.println("output : " + Arrays.toString(output));

        System.out.println("Test #2 : Remove number from empty array");
        int[] empty = {}; //empty array
        output = remove(empty, 23);
        System.out.println("input : " + Arrays.toString(empty) + ", remove 23");
        System.out.println("output : " + Arrays.toString(output));

        System.out.println("Test #3 : Remove number from array, without target number");
        int[] withoutTarget = {1, 2, 3, 4, 5, 6}; //empty array
        output = remove(withoutTarget, 12);
        System.out.println("input : " + Arrays.toString(withoutTarget) + ", remove 12");
        System.out.println("output : " + Arrays.toString(output));

        System.out.println("Test #4 : Delete element from array with only target numbers");
        int[] allWithTarget = {1, 1, 1, 1, 1, 1, 1};
        output = remove(allWithTarget, 1);
        System.out.println("input : " + Arrays.toString(allWithTarget) + ", remove 1");
        System.out.println("output : " + Arrays.toString(output));
    }


    /*
     * Removing a number from integer array with the help of LinkedList class
     */
    public static int[] removeNumber(int[] input, int number) {
        List<Integer> result = new LinkedList<Integer>();
        for (int item : input) {
            if (item != number) {
                result.add(item);
            }
        }
        return ArrayUtils.toPrimitive(result.toArray(new Integer[]{}));
    }


    /*
     * Removing element from array without using Collection class
     */
    public static int[] remove(int[] numbers, int target) {
        int count = 0;
        
        // loop over array to count number of target values.
        // this required to calculate length of new array
        for (int number: numbers) {
            if (number == target) {
                count++;
            }
        }

        // if original array doesn't contain number to removed
        // return same array
        if (count == 0) {
            return numbers;
        }

        int[] result = new int[numbers.length - count];
        int index = 0;
        for (int value : numbers) {
            if (value != target) {
                result[index] = value;
                index++;
            }
        }
        numbers = null; // make original array eligible for GC          return result;
    }
}

Output:
Test #1 : General case to remove number  22
input : [42, 322, 22, 11, 22, 33, 16], remove 22
output : [42, 322, 11, 33, 16]

Test #2 :  Remove number from empty array
input : [], remove 23
output : []

Test #3 : Remove number from array, without target number
input : [1, 2, 3, 4, 5, 6], remove 12
output : [1, 2, 3, 4, 5, 6]

Test #4 : Delete element from array with only target numbers
input : [1, 1, 1, 1, 1, 1, 1], remove 1
output : []


From the output, it's clear that our solution is working as expected. When we tested with an array where we have multiple target numbers it worked fine. We have also tested our solution with an empty array, an array which doesn't contain the value to be removed and an array containing the only value to be removed. It worked fine in all these scenario. You can createJUnit tests to capture each of these conditions and let me know if you still found any bug or typo in the code.


That's all about how to remove numbers from an array in Java. You have now learned two ways to delete an element from an array in Java. Though we have seen the example of removing the number from a numeric array, the algorithm is generic and will work with all types of array. You just need to create separate methods to accept different types of array e.g. method to remove an element from a long array or float array or String array.

0 comments:

Post a Comment