2.3.  Develop code that uses the Consumer interface


The java.util.function.Consumer<T> interface defines an abstract method named accept that takes an object of generic type T and returns no result (void):

package java.util.function;

public interface Consumer<T extends Object> {

    public void accept(T t);



You might use this interface when you need to access an object of type T and perform some operations on it. For example, you can use it to create a method processList, which takes a list of objects and applies an operation on each element of that list. In the following listing you use this processList method combined with a lambda to print all the elements of the list:

public class ConsumerDemo<T extends Object> {

    public void processList(List<T> list, Consumer<T> cons) {
        for(T s : list) {

    public static void main(String[] args) {
        List<String> l = Arrays.asList(new String[] {"Java", "8", "is", "great", "!"});
        Consumer<String> c = s -> System.out.print(String.format("%s ", s));
        new ConsumerDemo<String>().processList(l, c);


output is:

Java 8 is great !

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Exam 1Z0-810: Upgrade to Java SE 8 Programmer Quiz