Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the elements of an array which are equal in value?

Tags:

java

arrays

Using ArrayUtills in java code it is possible to remove an element from an java array. Below is the code which removes an element at a particlular index (in the code it is '2', which removes element value equalto '10'.

import java.util.Arrays;

import org.apache.commons.lang3.ArrayUtils;


public class RemoveObjectFromArray{

 public static void main(String args[]) {


     int[] test = new int[] { 10, 13, 10, 10, 105};

     System.out.println("Original Array : size : " + test.length );
     System.out.println("Contents : " + Arrays.toString(test));

     //let's remove or delete an element from Array using Apache Commons ArrayUtils
     test = ArrayUtils.remove(test, 2); //removing element at index 2

     //Size of array must be 1 less than original array after deleting an element
     System.out.println("Size of array after removing an element  : " + test.length);
     System.out.println("Content of Array after removing an object : "
                       + Arrays.toString(test));

 } }

It gives the output as:

run:
Original Array : size : 5
Contents : [10, 13, 10, 10, 105]
Size of array after removing an element  : 4
Content of Array after removing an object : [10, 13, 10, 105]

How the code can be amended to get the following output:

run:
Original Array : size : 5
Contents : [10, 13, 10, 10, 105]
Size of array after removing an element  : 2
Content of Array after removing an object : [ 13, 105]
like image 449
Soon Avatar asked Dec 26 '22 08:12

Soon


2 Answers

Try this code

while (ArrayUtils.contains(test, 10))  {
  //let's remove or delete an element from Array using Apache Commons ArrayUtils
  test = ArrayUtils.removeElement(test, 10); //removing element with value 10
}

It should solve your problem.

like image 122
Jens Avatar answered Dec 28 '22 06:12

Jens


I would use an ArrayList in your case but if you want to stick with your array you can do the following:

int count = 0;
for(int i = 0; i < test.length; i++){
  if (test[i] == 10) {
    count++;
  }
 }
 int[] newTest = new int[count];
 count = 0;
 for( int = 0; i < test.length; i++){
   if(test[i] != 10){
     newTest[count++] = test[i];
   }
  }

i didn't test it

like image 20
Barbe Rouge Avatar answered Dec 28 '22 06:12

Barbe Rouge