Java 8 Consumer Examples

In Java 8, Consumer is a functional interface; it takes an argument and returns nothing.


@FunctionalInterface
public interface Consumer<T> {
  void accept(T t);
}

1. Consumer

Java8Consumer1.java

package com.mkyong.java8;

import java.util.function.Consumer;

public class Java8Consumer1 {

    public static void main(String[] args) {

        Consumer<String> print = x -> System.out.println(x);
        print.accept("java");   // java

    }

}

Output


java

2. Higher Order Function

2.1 This example accepts Consumer as an argument, simulates a forEach to print each item from a list.

Java8Consumer2.java

package com.mkyong.java8;

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

public class Java8Consumer2 {

    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

        // implementation of the Consumer's accept methods.
        Consumer<Integer> consumer = (Integer x) -> System.out.println(x);
        forEach(list, consumer);

        // or call this directly
        forEach(list, (Integer x) -> System.out.println(x));

    }

    static <T> void forEach(List<T> list, Consumer<T> consumer) {
        for (T t : list) {
            consumer.accept(t);
        }
    }

}

Output


1
2
3
4
5
1
2
3
4
5

2.2 Same forEach method to accept Consumer as an argument; this time, we will print the length of the string.

Java8Consumer3.java

package com.mkyong.java8;

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

public class Java8Consumer3 {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("a", "ab", "abc");
        forEach(list, (String x) -> System.out.println(x.length()));

    }

    static <T> void forEach(List<T> list, Consumer<T> consumer) {
        for (T t : list) {
            consumer.accept(t);
        }
    }

}

Output


1
2
3

See the flexibility?

References

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar