❮ Previous Next ❯

Java Consumer Interface

It is a functional interface present in java.util.function package.

It contains an abstract accept() and a default and Then() method.

It can be used as the assignment target for a lambda expression or method reference.

The Consumer Interface accepts a single argument.

It does not return any result.


Java Consumer Interface Example 1

import java.util.function.Consumer;
public class ConsumerInterfaceExample1
   {    
   static void print(String name)    
      {
          System.out.println("Hello "+name);
      }
      static void show(int val)
      {
          System.out.println(val);
      }
      public static void main(String[] args)
      {
          // Referring method to String type Consumer interface
          consumer1.accept("Sanghamitra"); // Calling Consumer method
          Consumer<String> consumer1 = ConsumerInterfaceExample1::print;
          // Referring method to Integer type Consumer interface
          Consumer consumer2 = ConsumerInterfaceExample1::show;
          consumer2.accept(100); // Calling Consumer method
      }
   }

OUTPUT:
Hello Sanghamitra
100

JAVA Consumer Interface Example2

importjava.util.ArrayList;
importjava.util.List;
importjava.util.function.Consumer;
public class ConsumerInterfaceExample2
   {    
   static void addList(List l)    
      {
         // Return sum of list values
         int result = l.stream()
            .mapToInt(Integer::intValue)
            .sum();
         System.out.println("Sum of values: "+result);
      }
         public static void main(String[] args)
         {
            List list = new ArrayList();
            list.add(1);
            list.add(2);
            list.add(3);
            list.add(4);
          // Referring method to String type Consumer interface
         Consumer> consumer = ConsumerInterfaceExample::addList;
         consumer.accept(list);         // Calling Consumer method
         }
    }
OUTPUT:
Sum of values: 10

❮ Previous Next ❯










  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved