tags:

views:

119

answers:

2
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);
}
+3  A: 

That's because your Util.filter runs over empty filteredCollection which it creates in the beginning.

Dmitry
+4  A: 

First of all, don't write this kind of code yourself. There's Google Collections for that.

Having said that: Try to iterate over target instead of over filteredCollection in your filter() method, that should fix it.

Jorn
Thanks Jorn. It resolved. I've overseen that, as Eclipse has generated my 'for' loop.BTW, do you think it is worth to add a jar just for using one of its method. Just asking your opinion on this :) Cheers.
HanuAthena
For just this one method, probably not. But since it's open source, you can always rip that one method out of Google Collections and copy it to your source. The plus on including the jar is, you get access to all classes and methods in it, which can probably use to do other things to collections. If this happens a lot, the dependency makes your code a lot more consistent, having just library calls to operate on collections instead of writing your own method for everything.
Jorn