Reputation: 422
I have one filter Method using Predicate Interface to filter List on some conditions.
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;
}
I have one Integer array List as List arraIntegerList=Arrays.asList(1,2,3,3,4);
While calling above method it is giving compilation error.
System.out.println(filter(arraIntegerList,(int i)->(i>2)));
Why It is giving compilation error while same list with String is working fine.
Upvotes: 2
Views: 2010
Reputation: 2300
The lambda parameter types must exactly match with the method description. Since (int i)
doesn't match with the generic method description filter(List<T> list,Predicate<T> predicate)
and generics doesn't work with primitives.
So you need to provide the parameterized type.
System.out.println(filter(arraIntegerList, (Integer i) -> (i > 2)));
And you can let the compiler to infer the type though. In that case you can write -
System.out.println(filter(arraIntegerList, i -> (i > 2)));
Upvotes: 0
Reputation: 393841
You need to give the List a parameterized type, and the lambda's parameter must match the parameter of the List.
For example, this works :
List<Integer> arraIntegerList=Arrays.asList(1,2,3,3,4);
System.out.println(filter(arraIntegerList,(Integer i)->(i>2)));
Output :
[3, 3, 4]
As Stuart Marks commented, this also works :
List<Integer> arraIntegerList=Arrays.asList(1,2,3,3,4);
System.out.println(filter(arraIntegerList,i->(i>2)));
Upvotes: 4