Part-3 Functional Interface (Consumer)

Published: (March 3, 2026 at 03:04 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Consumer

Consumer is a functional interface in java.util.function.
It represents an operation that takes one input and returns nothing.

Core method

void accept(T t)

Extra methods in Consumer

  • andThen(Consumer after) – Chains two Consumers together.
    The current Consumer is executed first, followed by the after Consumer.

Example

Consumer print = s -> System.out.println(s);
Consumer printUpper = s -> System.out.println(s.toUpperCase());

Consumer combined = print.andThen(printUpper);

combined.accept("hello");
// Output:
// hello
// HELLO

Specialized Consumers

BiConsumer

Represents an operation that takes two inputs and returns nothing.

BiConsumer printNameAge =
    (name, age) -> System.out.println(name + " is " + age + " years old");

printNameAge.accept("Ravi", 25);
// Output: Ravi is 25 years old

Primitive Consumer Interfaces

When dealing with primitive types, specialized consumer interfaces avoid boxing/unboxing overhead.

IntConsumer

A consumer that takes an int.

IntConsumer printSquare = n -> System.out.println(n * n);
printSquare.accept(5); // Output: 25

LongConsumer

A consumer that takes a long.

LongConsumer printHalf = l -> System.out.println(l / 2);
printHalf.accept(100L); // Output: 50

DoubleConsumer

A consumer that takes a double.

DoubleConsumer printDoubleValue = d -> System.out.println(d * 2);
printDoubleValue.accept(3.5); // Output: 7.0

See you soon… we will meet at the next amazing blog!

0 views
Back to Blog

Related posts

Read more »

Part-4 Functional Interface(Function)

Functional Interface: Function A functional interface in java.util.function that represents a transformation: it takes an input of type T and produces an outpu...