Java — Generic methods and predicates
Use a type parameter and Predicate to share a counting algorithm across different element types.
A simple example
Test one value with a predicate
- Start with Integer 2
- Do this Test whether it is positive
- Result true
import java.util.function.Predicate;
class Main {
public static void main(String[] args) throws Exception {
Predicate<Integer> positive = n -> n > 0;
System.out.println(positive.test(2));
}
}
true
Pass a condition to a generic method
The type parameter T connects the list element type to the Predicate. Each lambda is type-checked against its list. The same counting method works for both strings and integers.
A club register needs two counts. One rule counts positive quantities and another counts nonempty names. The routine can apply either rule and returns two matches for each sample.
Run the example
Java 17 or later. Run these commands from the directory containing the example.
java Main.java
import java.util.List;
import java.util.function.Predicate;
class Main {
static <T> long countMatching(List<T> items, Predicate<T> test) {
return items.stream().filter(test).count();
}
public static void main(String[] args) {
System.out.println(countMatching(List.of(-1, 4, 7), n -> n > 0));
System.out.println(countMatching(List.of("Ada", "", "Lin"), s -> !s.isEmpty()));
}
}
2 2
Two integers are positive and two strings are nonempty. Both calls print 2 even though they test different conditions.
Try it yourself
What happens with an empty list?
Check your answer
The stream has no matching elements, so count returns zero.