Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter java.util.Collection in Java

I wrote a util class to filter elements in java.util.Collection as follows:

public class Util{
  public static <T> void filter(Collection<T> l, Filter<T> filter) {
    Iterator<T> it= l.iterator();
    while(it.hasNext()) {
      if(!filter.match(it.next())) {
        it.remove();
      }
    }
  }
}

public interface Filter<T> {
  public boolean match(T o);
}

Questions:

  1. Do you think it's necessary to write the method?
  2. Any improvement about the method?
like image 905
卢声远 Shengyuan Lu Avatar asked Jun 17 '26 18:06

卢声远 Shengyuan Lu


1 Answers

You should allow any Filter<? super T> not just Filter<T>.

Clients might also want to have a method that returns a new Collection instead:

public static <T> Collection<T> filter(Collection<T> unfiltered, 
    Filter<? super T> filter)
like image 167
AdamStevenson Avatar answered Jun 19 '26 09:06

AdamStevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!