Part-3 Functional Interface (Consumer)
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 twoConsumers together.
The currentConsumeris executed first, followed by theafterConsumer.
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!