Java 8 Consumer examples

Consumer definition

Consumer takes single argument and do not return any result.
Here is the definition of Consumer interface.



@FunctionalInterfacepublic
interface Consumer<T> {
/**
* * Performs this operation on the given argument. * * @param t the input
* argument
*/
void accept(T t);


default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> {
accept(t);
after.accept(t);
};
}
}

It has a functional method called accept() and default methodandThen().

Consumer examples

accept() method example

Let’s use Consumer interface to print String:

mport java.util.function.Consumer;
 
public class Java8ConsumerExample {
 
public static void main(String[] args) {
 
  Consumer<String> consumerString=s->System.out.println(s);
  consumerString.accept(“Arpit”);
}
}

We have created consumer object which takes String object as input and print it.It is simple use of Consumer interface to print String.
When you run above program, you will get below output:Arpit

default andThen() method example

As per java docs:
Returns a composed Consumer that performs, in sequence, this operation followed by the after operation. If performing either operation throws an exception, it is relayed to the caller of the composed operation. If performing this operation throws an exception, the after operation will not be performed.

import java.util.function.Consumer;
 
public class Java8ConsumerExample {
 
public static void main(String[] args) {
 
     Consumer<String> firstC = x -> System.out.println(x.toLowerCase());
     Consumer<String> secondC = y -> System.out.println(y.toUpperCase());
 
     Consumer<String> result = firstC.andThen(secondC);
 
    result.accept(“Arpit”);
}
}

Output:arpit
ARPIT

As you can see, we have created two consumers and used andThen() method to create composite consumer. When we called accept() method on composite consumer, both the consumers are called in sequence.

Consumer foreach example

Let’s say you have Student class as below:

public class Student {
 
    private int id;
    private String name;
    private String gender;
    private int age;
 
    public Student(int id, String name, String gender, int age) {
        super();
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.age = age;
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getGender() {
        return gender;
    }
 
    public void setGender(String gender) {
        this.gender = gender;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    @Override
    public String toString() {
        return “Student [id=” + id + “, name=” + name + “, gender=” + gender + “, age=” + age + “]”;
    }
}
 

Now let’s create Consumer object in main class and pass it to forEach method of list:

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
 
public class Java8ConsumerStudentExample {
 
    public static void main(String[] args) {
 
        List<Student> studentList = createStudentList();
        // Creating Consumer for student object which will be used in forEach method of
        // list
        Consumer<Student> consumerForStudent = s -> System.out.println(s);
        studentList.forEach(consumerForStudent);
    }
 
    public static List<Student> createStudentList() {
        List<Student> studentList = new ArrayList<>();
        Student s1 = new Student(1, “Arpit”, “M”, 19);
        Student s2 = new Student(2, “John”, “M”, 17);
        Student s3 = new Student(3, “Mary”, “F”, 14);
        Student s4 = new Student(4, “Martin”, “M”, 21);
        Student s5 = new Student(5, “Monica”, “F”, 16);
        Student s6 = new Student(6, “Ally”, “F”, 20);
 
        studentList.add(s1);
        studentList.add(s2);
        studentList.add(s3);
        studentList.add(s4);
        studentList.add(s5);
        studentList.add(s6);
        return studentList;
    }
}

When you run above program, you will get below output:name : Arpit == Age : 19
name : John == Age : 17
name : Mary == Age : 14
name : Martin == Age : 21
name : Monica == Age : 16
name : Ally == Age : 20

We have created consumer object which takes student object as input and print it.Above created consumer object is then passed to foreach() method of Iterable interface.

 default void forEach(Consumer<? super T> action{        
Objects.requireNonNull(action);       
 for (T t : this) {            
action.accept(t);       
  }   

As you can see, foreach() method takes consumer as input and calls accept() method on each object of Iterable.
That’s all about Java 8 consumer example.

Popular posts from this blog

Window function in PySpark with Joins example using 2 Dataframes (inner join)

Complex SQL: fetch the users who logged in consecutively 3 or more times (lead perfect example)

Credit Card Data Analysis using PySpark (how to use auto broadcast join after disabling it)