为什么这是错的?关于java 8流媒体

JSP*_*r01 3 java collections java-8

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

参数类型错误

我正在学习java 8流媒体功能,这是我有问题的代码......

我不知道为什么参数intList不符合filter()方法.Java应该知道<T>Integer这里,对吗?

Jon*_*eet 7

我还不确定你为什么会得到那个特定错误,但问题是你的方法声明它会返回Collection<T>,但是你试图将结果分配给a List<T>.如果您将声明更改filter为:

public static <T> List<T> filter(Collection<T> collection, Filter<T> filter)
Run Code Online (Sandbox Code Playgroud)

...然后它编译没有问题.

  • @ManuZi:但这是一个*弱*解决方案 - 该方法肯定会返回一个列表,因为它使用`Collectors.toList()`,所以指定它返回一个列表是有意义的... (2认同)