Java Lambda - Consumer accept example








Consumer accept performs operation on the given argument.

Syntax

accept has the following syntax.

void accept(T t)

Example

The following example shows how to use accept.

import java.util.function.Consumer;

public class Main {
  public static void main(String[] args) {
    Consumer<String> c = (x) -> System.out.println(x.toLowerCase());
    c.accept("Java2s.com");
  }
}

The code above generates the following result.





Example 2

The following code shows how to pass Consumer to forEach method.

/*from  w w  w . j av a  2 s. c om*/
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class Main {

  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    numbers.forEach(new Consumer<Integer>() {
        @Override
        public void accept(Integer integer) {
            System.out.println(integer);
        }
    });

  }
}

The code above generates the following result.