开发者

whats wrong with this code? It is not filtering the 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);
    }

}

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);
}


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜