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);
}
}
where my Utils.filter() method is :
public static <T> Collection<T> filter(Collection<T> target,
Predicate<T> predicate) {
Collection<T> filteredCollection = new ArrayList<T>();
for (T t : filteredCollection) {
if (predicate.apply(t)) {
filteredCollection.add(t);
}
}
return filteredCollection;
}
and the Prdicate:
public interface Predicate<T> {
public boolean apply(T type);
}