DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Jayaprakash has posted 2 posts at DZone. View Full User Profile

Collection Filtering In Java

11.15.2009
| 11086 views |
  • submit to reddit
        // filtering a Collection

public class CollectionsFilter {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5, 6, 7,
                        8, 9, 10 });
        Collection<Integer> evenNumbers = Utils.filter(list,
                        new Predicate<Integer>() {
                                public boolean apply(Integer i) {
                                        if (i % 2 == 0) {
                                                return true;
                                        }
                                        return false;
                                }
                        });

        Collection<Integer> oddNumbers = Utils.filter(list,
                        new Predicate<Integer>() {
                                public boolean apply(Integer i) {
                                        if (i % 2 != 0) {
                                                return true;
                                        }
                                        return false;
                                }
                        });
        System.out.println("EVEN Numbers > " + evenNumbers);
        System.out.println("ODD Numbers > " + oddNumbers);
    }
}
Utils.filter() method :
public static <T> Collection<T> filter(Collection<T> target,
                Predicate<T> predicate) {
  Collection<T> filteredCollection = new ArrayList<T>();
   for (T t : target) {
     if (predicate.apply(t)) {
          filteredCollection.add(t);
     }
   }
   return filteredCollection;
}
and Predicate:
public interface Predicate<T> {
    public boolean apply(T type);
}