Java Consumer Interface

  • accept() -> It takes parameter, doing some stuff and doesn’t return anything.
  • andThen() -> It chains the consumer together so that they can run sequentially when the accept() method is called.
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
Consumer<String> consumer = s-> System.out.println(“Hello, I am “ + s);consumer.accept("Yigit");Output : Hello, I am Yigit
/// Define methodsConsumer<String> sendSmsNotifactionToUser = username -> System.out.println("Sended Sms Notification to : "+username);Consumer<String> sendMailNotifactionToUser = username -> System.out.println("Sended Mail Notification to : "+username);Consumer<String> sendPushNotificationToUser = username -> System.out.println("Sended Push Notification to : "+username);/// Send Notifications to User
sendSmsNotifactionToUser.andThen(sendMailNotifactionToUser).andThen(sendPushNotificationToUser).accept("Yigit");
Output :Sended Sms Notification to : Yigit
Sended Mail Notification to : Yigit
Sended Push Notification to : Yigit
  • IntConsumer: It takes int parameter.
  • LongConsumer: It takes long parameter .
  • DoubleConsumer: It takes double parameter.
  • BiConsumer: It takes parameter which types T and U.
  • ObjIntConsumer: It take parameters which types T and int .
  • ObjDoubleConsumer: It take parameters which types T and double .
  • ObjLongConsumer: It take parameters which types T and long .

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yigit Kader

Yigit Kader

Software Engineer , Berlin , @devyigitk twitter