What are the purposes of functional interfaces like Consumer<T>, DoubleConsumer, IntConsumer, and LongConsumer?
sobes.tech AI
Answer from AI
Functional interfaces Consumer<T>, DoubleConsumer, IntConsumer, and LongConsumer are used to represent operations that accept a single input argument and do not return a result. They are part of the java.util.function package.
Consumer<T>: Accepts an argument of any typeT.DoubleConsumer: Accepts an argument of typedouble. This is a primitive specialization ofConsumer, which avoids autoboxing and is more efficient.IntConsumer: Accepts an argument of typeint. Also a primitive specialization for efficiency.LongConsumer: Accepts an argument of typelong. Another primitive specialization.
The main use of these interfaces is in Lambdas and method references. They are often used in Java Stream API for performing side effects on stream elements, such as printing to the console or modifying external state.
Example of using Consumer<T>:
// Creating a Consumer that prints a string
Consumer<String> printConsumer = s -> System.out.println(s);
// Applying the Consumer
printConsumer.accept("Hello, world!");
// Using in a stream
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream().forEach(n -> System.out.println(n)); // Using Consumer (lambda)
Example of using IntConsumer:
// Creating an IntConsumer that prints a number
IntConsumer printIntConsumer = i -> System.out.println(i);
// Applying the IntConsumer
printIntConsumer.accept(10);
// Using in a primitive int stream
IntStream.range(1, 5).forEach(printIntConsumer); // More efficient for primitive types
Primitive specializations (DoubleConsumer, IntConsumer, LongConsumer) should be preferred over their generic Consumer<T> counterparts when working with primitive types to improve performance by avoiding boxing/unboxing operations.