Removal of negative numbers from an array in Java

Java 8Object Oriented ProgrammingProgramming

Following program shows how to remove negative numbers from an array.

Example

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Tester {
   public static void main(String[] args) {
      List<Integer> objArray = new ArrayList<Integer>();
      objArray.clear();
      objArray.add(2);
      objArray.add(-3);
      objArray.add(4);
      System.out.println("Array before removing an element "+objArray);
      Iterator<Integer> iterator = objArray.iterator();
     
         while(iterator.hasNext()) {
         Integer next = iterator.next();
         if(next < 0) {
            iterator.remove();
         }
      }
      System.out.println("Array after removing an element"+objArray);
   }
}

Output

Array before removing an element [ 2, -3, 4 ]
Array after removing an element [ 2, 4 ]
raja
Published on 06-Feb-2018 10:57:48
Advertisements