Java Consumer Interface

Yigit Kader
2 min readMar 7, 2022

Consumer interface is a functional interface. in this way, functional interfaces can be used as Lambda. Defined under java.util.function.*

Consumer interfaces have methods which names are “accept()” and “andThen()”

  • 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); };
}
}

Lets create a consumer..

Consumer<String> consumer = s-> System.out.println(“Hello, I am “ + s);consumer.accept("Yigit");Output : Hello, I am Yigit

And now lets try chaining with andThen() method

Lets say we have 3 different methods about notification and we need to send this notifications to user. We can handle like this way :

/// 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

While using the consumer interface, we used generic types, but if we wanted to use primitive types, Java prepared auxiliary interfaces for us. These;

  • 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 .

Now we have come to the end of this topic, Have a nice day :)

--

--