Saturday, 31 May 2014

ArrayList : removeIf : Remove element if condition satisfied

public boolean removeIf(Predicate<? super E> filter)
Removes all of the elements of this collection that satisfy the given predicate.

import java.util.function.*;

class MyPredicate<T> implements Predicate<T>{
  T var1;
  public boolean test(T var){
  if(var1.equals(var)){
   return true;
  }
  return false;
  }
}

import java.util.*;

class ArrayListRemoveIf{
 public static void main(String args[]){
  ArrayList<Integer> myList;
  MyPredicate<Integer> filter;
  
  myList = new ArrayList<> ();
  filter = new MyPredicate<> ();
  
  filter.var1 = 10;
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(20);
  myList.add(10);
  myList.add(30);
  myList.add(10);
  myList.add(40);
  myList.add(10);
  
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  System.out.print("Removing all 10's from myList");
  System.out.println(myList.removeIf(filter));
  
  System.out.println("Elements in myList are");
  System.out.println(myList);
 }
}

Output
Elements in myList are
[10, 20, 10, 30, 10, 40, 10]
Removing all 10's from myListtrue
Elements in myList are
[20, 30, 40]


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment