Lesson contents

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

  1. Start with Integer 2
  2. Do this Test whether it is positive
  3. Result true
The predicate expects an Integer. Its test method evaluates the comparison and returns a boolean.
Main.java
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));
    }
}
Output
true
Advertisements

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.

Positive quantities: 4 and 7. Nonempty names: Ada and Lin. Each count: 2 matches.
Reuse one counting routine

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
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()));
    }
}
Output
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.

Java language tutorials

Related tags

  • Java
  • generics
  • predicates
  • streams