Java Stream How to - Create Consumer with lambda








Question

We would like to know how to create Consumer with lambda.

Answer

import java.util.function.Consumer;
//from   w ww .  ja v  a2  s  .c om
public class Main {
  public static void main(String... args) {
    Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName);
    greeter.accept(new Person("First", "Last"));
  }
}
class Person {
  String firstName;
  String lastName;

  Person() {}

  Person(String firstName, String lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
  }
}

The code above generates the following result.