I want to create a simple general method for counting numbers after applying a filter

I want to create a simple general method for counting numbers after applying a filter.

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

This gives me this error:

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

CAP # 1 extends the number from capture? extends number

CAP # 2 extends the number from capture? extends number

+6
source share
1 answer

You cannot use a wildcard like this, since the second parameter depends on the first! Your version implies that you want to take a collection of apples and then apply a banana predicate to it.

: -unkown type; :

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

: count() ; , . , , int, () .

+6

Source: https://habr.com/ru/post/1017265/


All Articles