In Java 8, Consumer is a functional interface, it takes an argument and returns nothing. An interface with just one abstract method is referred to as a functional interface. They are limited to displaying only one type of feature. Lambda expressions can be used to describe a functional interface instance starting with Java 8. Some examples of usable interfaces include Runnable, ActionListener, and Comparable.

Consumer<T> can be used in any case where an object must be consumed, i.e. taken as input, and some operation on the object must be performed without returning a result.

When would you use a functional interface ? An interface with only one abstract method is called Functional Interface. It is not mandatory to use @FunctionalInterface, but it’s best practice to use it with functional interfaces to avoid addition of extra methods accidentally.


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

Consumer

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.

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.


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

For more information about Java 8 features , try to read our tutorials

References

Tagged:

Commentaires

  1. Pingback: forEach Java 8 Examples » JavaTuto

Laisser un commentaire