Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Create a simple generic method to count after applying filter

Tags:

java

generics

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

like image 902
Subhabrata Mondal Avatar asked May 15 '17 10:05

Subhabrata Mondal


People also ask

How can we write a generic sort method?

Using Java Generic concept, we might write a generic method for sorting an array of objects, then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array elements.

How do you declare a generic method How do you invoke a generic method?

Generic MethodsAll generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example). Each type parameter section contains one or more type parameters separated by commas.


1 Answers

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.

like image 200
GhostCat Avatar answered Sep 18 '22 07:09

GhostCat