Java Stream How to - Use Consumer as parameter








Question

We would like to know how to use Consumer as parameter.

Answer

import java.util.function.Consumer;
/*from  ww  w . j a v a2  s  .  co  m*/
public class Main {
  public static void main(String[] args) {
    processCustomer(12, (Customer c) -> System.out.println("Hello!"));
  }

  public static void processCustomer(int id,Consumer<Customer> makeCustomerHappy) {
    Customer c = Database.getCustomerWithId(id);
    makeCustomerHappy.accept(c);
  }
}

class Customer {
}
class Database {
  static Customer getCustomerWithId(int id) {
    return new Customer();
  }
}

The code above generates the following result.