Why is it wrong? about java 8 stream

public interface Filter<M> {

    boolean match(M m);

    public static <T> Collection<T> filter(Collection<T> collection, Filter<T> filter) {
        return collection.stream().filter(filter::match).collect(Collectors.toList());
    }

    ////////////////////////////////////////////////////////////////

    public static void main(String[] args) {
        ArrayList<Integer> intList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8));
        System.out.println(intList);

        List<Integer> list = filter(intList, null);

        System.out.println(list);
    }
}

      

parameter type error

I am looking into java 8 streaming feature and this is my problematic code ...

I don't know why the argument intList

doesn't match the method filter()

. Java needs to know <T>

is Integer

here, right?

+3


source to share


1 answer


I'm not sure yet why you are getting this particular error, but the problem is your method declares what it will return Collection<T>

, but you are trying to assign the result List<T>

. If you change your ad filter

to:

public static <T> List<T> filter(Collection<T> collection, Filter<T> filter)

      



... then it compiles without issue.

+7


source







All Articles