Java.Java8.What are the functional interfaces Consumer, DoubleConsumer, IntConsumer, and LongConsumer?

These are used when you accept a value and do something with it, but you don’t return a result.


✅ 1. Consumer<T>

Package: java.util.function

  • Represents an operation that takes a single input of type T and returns no result (void).
  • Typically used for operations like logging, printing, modifying, or sending data.
@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}

🧠 Example:

Consumer<String> printUpper = s -> System.out.println(s.toUpperCase());
printUpper.accept("hello"); // Output: HELLO

🔧 Use Case:

Used with forEach() in streams:

List<String> names = List.of("Alice", "Bob");
names.forEach(printUpper);

You can also chain consumers using .andThen():

Consumer<String> print = System.out::println;
Consumer<String> printAndShout = print.andThen(s -> System.out.println("!!!"));
printAndShout.accept("Wow"); // Output: Wow\n!!!

✅ 2. IntConsumer

  • For primitives of type int.
  • Avoids boxing overhead.
@FunctionalInterface
public interface IntConsumer {
    void accept(int value);
}

🧠 Example:

IntConsumer doubler = x -> System.out.println(x * 2);
doubler.accept(4); // Output: 8

✅ 3. LongConsumer

Same idea for long values.

@FunctionalInterface
public interface LongConsumer {
    void accept(long value);
}

Example

LongConsumer showTime = t -> System.out.println("Timestamp: " + t);
showTime.accept(System.currentTimeMillis());

✅ 4. DoubleConsumer

For double values.

@FunctionalInterface
public interface DoubleConsumer {
    void accept(double value);
}

🧠 Example:

DoubleConsumer showSquare = d -> System.out.println("Square: " + (d * d));
showSquare.accept(3.5); // Output: Square: 12.25

🔄 Summary Table:

InterfaceInput TypeReturn TypeUse Case Example
Consumer<T>Tvoids -> System.out.println(s)
IntConsumerintvoidx -> System.out.println(x * 2)
LongConsumerlongvoidl -> System.out.println(l)
DoubleConsumerdoublevoidd -> System.out.println(d * d)
This entry was posted in Без рубрики. Bookmark the permalink.