8
votes

I want to create a simple generic method to count the numbers after applying the filter based on the provided predicate.

static int count(Collection < ? extends Number > numbers, Predicate < ? extends Number > predicate) {
  return numbers.stream().filter(predicate).count();
}

It gives me the following error:

incompatible types: Predicate cannot be converted to Predicate<? super CAP#2> where CAP#1, CAP#2 are fresh type-variables:

CAP#1 extends Number from capture of ? extends Number

CAP#2 extends Number from capture of ? extends Number

1
Thank you for your help. - Subhabrata Mondal

1 Answers

7
votes

You can't use the wildcard like this, as the second parameter depends on the first one! Your version implies that you want to take a Collection of Apples to then apply a Banana Predicate on that.

In other words: simply declare a not-unkown type parameter; and use that:

static <T extends Number> long count(Collection<T> numbers, Predicate <T> predicate) {

For the record: count() returns a long result; thus I changed the return type accordingly. If that is not what you want, you have to cast to int, but live with the (potential) loss of information.