Java 8 谓词泛型函数不接受整数列表

Java 8 predicate generic function is not accepting List of Integers

我有一种使用谓词接口在某些条件下过滤列表的过滤方法。

public static <T> List<T> filter(List<T> list,Predicate<T> predicate){
    List<T> result=new ArrayList<T>();
    for(T t:list){
        if(predicate.test(t)){
            result.add(t);
        }
    }
    return result;
}

我有一个整数数组 List as List arraIntegerList=Arrays.asList(1,2,3,3,4);

调用上述方法时出现编译错误。

System.out.println(filter(arraIntegerList,(int i)->(i>2)));

为什么在与 String 相同的列表工作正常时出现编译错误。

你需要给List一个参数化的类型,lambda的参数必须和List的参数匹配。

例如,这个有效:

List<Integer> arraIntegerList=Arrays.asList(1,2,3,3,4);
System.out.println(filter(arraIntegerList,(Integer i)->(i>2)));

输出:

[3, 3, 4]

正如 Stuart Marks 评论的那样,这也有效:

List<Integer> arraIntegerList=Arrays.asList(1,2,3,3,4);
System.out.println(filter(arraIntegerList,i->(i>2)));

lambda 参数类型必须与方法描述完全匹配。由于 (int i) 与通用方法描述不匹配 filter(List<T> list,Predicate<T> predicate) 泛型不适用于原语。 所以你需要提供参数化类型。

    System.out.println(filter(arraIntegerList, (Integer i) -> (i > 2)));

而且您可以让编译器推断类型。在那种情况下你可以写 -

    System.out.println(filter(arraIntegerList, i -> (i > 2)));