Java Stream How to - Create and use Consumer Lambda








Question

We would like to know how to create and use Consumer Lambda.

Answer

import java.util.function.Consumer;
//  w w  w.ja va  2s . c om
public class Main {
  public static void main(String[] args) {
    Message message = new Message("java2s.com");
    Person person = new Person("Peter");

    Consumer<Message> messageConsumer = (t) -> System.out.println(t);
    messageConsumer.accept(message);

    Consumer<Person> personConsumer = (t) -> System.out.println(t);
    personConsumer.accept(person);

  }

}

class Message {

  private String msg;

  public Message(String msg) {
    this.msg = msg;
  }

  public String getMessage() {
    return msg;
  }

  public String toString() {
    return getMessage();
  }
}

class Person {

  private String name;

  public Person(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public String toString() {
    return getName();
  }

}

The code above generates the following result.