DEV Community

Code Green
Code Green

Posted on

Explain Predicate and Consumer in Java

Predicate and Consumer in Java

Predicate

  • What: A functional interface in java.util.function representing a boolean-valued function of one argument.
  • Signature: boolean test(T t)
  • Common use: filtering, conditional checks (e.g., stream.filter).
  • Default/composed methods:
    • default Predicate<T> and(Predicate<? super T> other)
    • default Predicate<T> or(Predicate<? super T> other)
    • default Predicate<T> negate()
    • static <T> Predicate<T> isEqual(Object targetRef)
  • Example:
Predicate<String> isEmpty = String::isEmpty;
Predicate<String> startsWithA = s -> s.startsWith("A");
Predicate<String> combined = isEmpty.negate().and(startsWithA);
boolean ok = combined.test("Apple"); // true
Enter fullscreen mode Exit fullscreen mode

Consumer

  • What: A functional interface in java.util.function representing an operation that accepts a single input and returns no result.
  • Signature: void accept(T t)
  • Common use: performing actions (e.g., stream.forEach, side-effects, logging).
  • Default/composed method: default Consumer andThen(Consumer<? super T> after)
Consumer<String> print = System.out::println;
Consumer<String> exclaim = s -> System.out.println(s + "!");
Consumer<String> combined = print.andThen(exclaim);
combined.accept("Hello"); // prints "Hello" then "Hello!"
Enter fullscreen mode Exit fullscreen mode
List<String> names = List.of("Alice", "Bob", "Anna");
Predicate<String> startsWithA = s -> s.startsWith("A");
Consumer<String> printer = System.out::println;

names.stream()
     .filter(startsWithA)
     .forEach(printer); // prints "Alice" and "Anna"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)