Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

Functional Interfaces: Consumer and Predicate

Functional Interfaces in Java
  • A functional interface has exactly one abstract method.
  • It should be annotated with @FunctionalInterface.

Some common functional interfaces in the java.util.function package are:

  • Consumer: Accepts a value and performs an action (Return Type: void).
  • Predicate: Evaluates a condition (Return Type: boolean).
  • Function: Transforms an input to an output (Return Type: R).

Consumer

The Consumer interface includes the method void accept(T t), which takes an argument of type T and performs an operation on it.

Features of Consumer:

  • Chains multiple Consumer operations so that they execute in sequence using andThen.
  • Works seamlessly with forEach in the Stream API.

Example: Consumer


import java.util.function.Consumer;

public class ConsumerExample {
    public static void main(String[] args) {
        // A simple Consumer to print a message
        Consumer print = (x) -> System.out.println("Message: " + x);
        print.accept("Hello, Java!");
    }
}

    

Chaining Consumers Using andThen


import java.util.function.Consumer;

public class ConsumerChaining {
    public static void main(String[] args) {
        Consumer toUpperCase = (name) -> System.out.println(name.toUpperCase());
        Consumer toLowerCase = (name) -> System.out.println(name.toLowerCase());

        // Chain Consumers: First print in uppercase, then lowercase
        Consumer chainedConsumer = toUpperCase.andThen(toLowerCase);

        // Apply the chained consumer
        chainedConsumer.accept("Aashutosh Kumar");
        // Output:
        // AASHUTOSH KUMAR
        // aashutosh kumar
    }
}

    

Predicate

The Predicate interface provides a way to define reusable conditions. Some features include:

  • Use Predicate to define conditions.
  • It can be used for reusable conditional logic.
  • Predicates are useful in stream processing to create cleaner and more efficient code.
  • In Spring Boot development, predicates can help create dynamic queries that adapt to changing conditions.

Example: Predicate


import java.util.function.Predicate;

public class PredicateExample {
    public static void main(String[] args) {
        // Define a Predicate to check if a number is even
        Predicate isEven = (number) -> number % 2 == 0;

        // Test the Predicate
        System.out.println(isEven.test(4));  // Output: true
        System.out.println(isEven.test(5));  // Output: false
    }
}

    

Post a Comment

0 Comments