Java 8 consumer class(interface) example

In this example I will explains you how to use the consume class of the Java 8 and then write a code for iterating a collection.

Java 8 consumer class(interface) example

In this example I will explains you how to use the consume class of the Java 8 and then write a code for iterating a collection.

Java 8 consumer class(interface) example

How to use the Java 8 consumer class(interface)?

In this example program I will show you how you can use the consumer interface of the Java 8 to iterate through the collection and then print the value of the iterated data.

The Consumer is a functional interface added to the Java 8 which is used to assign the target for a lambda expression or method reference.

@FunctionalInterface
public interface Consumer<T>

The above interface is used to accept the single argument and it returns nothing. The functional method of this interface is accept(Object). In this example we will show you the usage of the accept() method.

Java 8 consumer example

Here is the complete code example of the program:

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.lang.Integer;
 
public class Java8ConsumerExample {
 
    public static void main(String[] args) {
         
        //Create a collection
        List arrList = new ArrayList();
        for(int i=0; i<20; i++) arrList.add(i);//Fill the values
         
        //Travesing through the array list
        arrList.forEach(new Consumer() {
             public void accept(Integer t) {
                System.out.println("Value is:"+t);
            }
         });
  }
}

If you run the example it will give you the following output:

Java 8 Consumer Example

Following is an example of Creating the implementation of the Consumer interface:

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.lang.Integer;
 
public class Java8ConsumerExample {
 
    public static void main(String[] args) {
         
        //Create a collection
        List arrList = new ArrayList();
        for(int i=0; i<20; i++) arrList.add(i);//Fill the values
         
        //Travesing through the array list
        arrList.forEach(new Consumer() {
             public void accept(Integer t) {
                System.out.println("Value is:"+t);
            }
         });

		//example of Consumer implementation
        ConsumerObject objAction = new ConsumerObject();
        arrList.forEach(objAction);

  }
}

//Consumer implementation example
class ConsumerObject implements Consumer{
 
    public void accept(Integer t) {
       System.out.println("Value is:"+t);
    }
 
 
}

Read more tutorials and example of Java 8.