๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Consumer Interface  


Introduction
  • Consumer interface is a functional interface in Java 8 that represents an operation which takes one argument and returns no result.
  • It is part of the java.util.function package.
  • Uses of Consumer Interface:
    • Used to perform operations like printing, logging, saving, etc., on an object.
    • Commonly used with forEach() method in collections and streams.
    • Helps write clean, functional-style code using lambda expressions.
    • Can be chained with andThen() method to perform multiple operations sequentially.
  • Syntax :
    public interface Consumer
    {
        void accept(T t);
        //some default methods are also present
    }
Programs:
  • 1. Simple program without lambda expression:
    import java.util.function.Consumer;
    
    public class MainApp
    {
        public static void main(String[] args)
        {
            // Consumer to print a message using anonymous class
            Consumer<String> printMessage = new Consumer<String>() {
                @Override
                public void accept(String msg) {
                    System.out.println("Message: " + msg);
                }
            };
    
            // Test messages
            printMessage.accept("Hello Java");
            printMessage.accept("Welcome to Consumer Interface");
        }
    }
  • 2. Program with lambda expression:
    import java.util.function.Consumer;
    
    public class MainApp
    {
        public static void main(String[] args)
        {
            // Consumer to print a message using lambda expression
            Consumer<String> printMessage = msg -> System.out.println("Message: " + msg);
    
            // Test messages
            printMessage.accept("Hello Java");
            printMessage.accept("Welcome to Consumer Interface");
        }
    }