• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Java Consumer Example – Functional Interface

January 11, 2021 by javainterviewpoint Leave a Comment

The Consumer Functional interface takes a single input and does not return anything. The consumer interface is located in java.util.function package. It has a Single Abstract Method (SAM) accept(), which accepts the generic object type T and doesn’t return any result.

Java Consumer Example

Java Consumer Example

Whenever we create a Lambda Expression, which takes a single input and doesn’t return any value, then the Consumer can be used as a target for the lambda expression.

Methods in Consumer Interface

  1. accept(T t) – This method takes a single generic argument T and doesn’t return any value
  2. default Consumer<T> andThen(Consumer<? super T> after) – This is a default method, returns a composed consumer. The input consumer will be executed, and on the result, the second consumer will be executed.

1. Java Consumer accept(T t) method example

The accept() method of the Consumer interface can take any object type as an argument and does not return anything

Let’s build a Consumer that prints element which is passed to it.

package com.javainterviewpoint;

import java.util.function.Consumer;

public class PrintConsumer
{
   public static void main(String[] args)
   {
      Consumer printer = str -> System.out.println(str);
      printer.accept("Welcome");
      printer.accept("JavaInterviewPoint");
   }
}

Output:

Welcome
JavaInterviewPoint

In the above code, we have created a Consumer that prints the string passed to it.

Consumer<String> printer = str -> System.out.println(str);

We can invoke the printer consumer by passing a string argument to the accept() method.

The Consumer interface can also be used in the Streams; the forEach() method of the stream takes the Consumer as its argument.

Let’s re-use the PrinterConsumer in a Stream to print the elements of the ArrayList.

package com.javainterviewpoint;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class PrintConsumer
{
   public static void main(String[] args)
   {
      Consumer printer = str -> System.out.println(str);

      List countryList = Arrays.asList("India", "Australia", "France",
            "Canada");
      countryList.stream().forEach(printer);
   }
}

Output:

India
Australia
France
Canada

The Consumer can be used on custom objects as well. Let’s create a consumer that capitalizes the student names.
Student.java

package com.javainterviewpoint;

public class Student
{
   private int id;
   private int mark;
   private String name;

   public Student()
   {
      super();
   }
   public Student(int id, int mark, String name)
   {
      super();
      this.id = id;
      this.mark = mark;
      this.name = name;
   }
   public int getId()
   {
      return id;
   }
   public void setId(int id)
   {
      this.id = id;
   }
   public int getMark()
   {
      return mark;
   }
   public void setMark(int mark)
   {
      this.mark = mark;
   }
   public String getName()
   {
      return name;
   }
   public void setName(String name)
   {
      this.name = name;
   }
   @Override
   public String toString()
   {
      return "Student [id=" + id + ", mark=" + mark + ", name=" + name + "]";
   }
}

CapitalizeConsumer.java

package com.javainterviewpoint;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class CapitalizeConsumer
{
   public static void main(String[] args)
   {
      List<String> studentList = new ArrayList<String>();
      studentList.add(new Student(1, 45, "Alice"));
      studentList.add(new Student(2, 65, "Bob"));
      studentList.add(new Student(3, 80, "Clair"));
      studentList.add(new Student(4, 20, "Dom"));

      Consumer<String> capsConsumer = name -> System.out
            .println(name.toUpperCase());

      studentList.stream().map(student -> student.getName())
            .forEach(capsConsumer);
   }
}

In the above code, we have created a consumer that capitalizes and prints the names passed to it.

Output:

ALICE
BOB
CLAIR
DOM

2. Consumer interface andThen() method example

The andThen() method of the Consumer interface, the input function will be executed first, and on the result, the second function (andThen) will be executed.

The first consumer will add 20 marks for each student, and the second consumer prints the student object.

package com.javainterviewpoint;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class StudentConsumer
{
   public static void main(String[] args)
   {
      List<Student> studentList = new ArrayList<Student>();
      studentList.add(new Student(1, 25, "Adam"));
      studentList.add(new Student(2, 35, "Bob"));
      studentList.add(new Student(3, 45, "Danny"));
      studentList.add(new Student(4, 55, "Will"));

      Consumer<List<Student>> addMarksConsumer = list ->
      {
         for (int i = 0; i < list.size(); i++)
         {
            list.get(i).setMark(list.get(i).getMark() + 20);
         }
      };

      Consumer<List<Student>> printConsumer = list -> list
            .forEach(System.out::println);

      addMarksConsumer.andThen(printConsumer).accept(studentList);
   }
}

In the above, we have the first consumer addMarksConsumer takes the Student marks and adds 20 to it, and the second consumer printConsumer prints the student object.

Since we have used addMarksConsumer.andThen(printConsumer), the addMarksConsumer will be executed first, and on top of it, the printConsumer gets executed

Output:

Student [id=1, mark=45, name=Adam]
Student [id=2, mark=55, name=Bob]
Student [id=3, mark=65, name=Danny]
Student [id=4, mark=75, name=Will]

Happy Learning !!

Filed Under: Java Tagged With: Consumer, Consumer Example, Consumer Interface, Functional Interface, Java Consumer Example, Java Consumer Interface

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·