Consumer:
- Consumer is an interface in java.
- A functional interface in
java.util.function. - 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.
- First executes the current Consumer, then executes the after Consumer.
Consumer<String> print = s -> System.out.println(s);
Consumer<String> printUpper = s -> System.out.println(s.toUpperCase());
Consumer<String> combined = print.andThen(printUpper);
combined.accept("hello");
// Output:
// hello
// HELLO
Specialized Consumers:
Java also provides specialized versions of Consumer for different use cases:
BiConsumer<T,U>
-Accepts two inputs, performs an action.
BiConsumer<String, Integer> printNameAge =
(name, age) -> System.out.println(name + " is " + age + " years old");
printNameAge.accept("Ravi", 25);
// Output: Ravi is 25 years old
Primitive Consumer Interfaces:
Normal Consumer uses objects (like Integer), but when dealing with primitives like int, long, or double, that would cause unnecessary boxing/unboxing. So we have these specialized interfaces to handle primitives efficiently.
1. IntConsumer
Definition: A Consumer that takes an int and performs an action.
IntConsumer printSquare = n -> System.out.println(n * n);
printSquare.accept(5); // Output: 25
2. LongConsumer
Definition: A Consumer that takes a long and performs an action.
LongConsumer printHalf = l -> System.out.println(l / 2);
printHalf.accept(100L); // Output: 50
3. DoubleConsumer
Definition: A Consumer that takes a double and performs an action.
DoubleConsumer printDoubleValue = d -> System.out.println(d * 2);
printDoubleValue.accept(3.5); // Output: 7.0
See u Soon... we will meet at the next Amazing blog!.....
Top comments (0)