In Java, "consumer" and "biconsumer" are functional interfaces defined in the java.util.function
package, introduced in Java 8 as part of the functional programming enhancements. These interfaces are part of the Java Function API and are commonly used with lambda expressions and the Streams API.
Consumer: The Consumer
interface represents an operation that takes a single input argument and returns no result. It has a single method called accept(T t)
that takes an argument of type T
and performs an operation on it.
import java.util.function.Consumer;
public class ExampleConsumer {
public static void main(String[] args) {
Consumer<String> printUpperCase = s -> System.out.println(s.toUpperCase());
printUpperCase.accept("hello");
}
}
BiConsumer: The BiConsumer
interface represents an operation that takes two input arguments and returns no result. It has a method called accept(T t, U u)
that takes two arguments of types T
and U
and performs an operation on them.
import java.util.function.BiConsumer;
public class ExampleBiConsumer {
public static void main(String[] args) {
BiConsumer<String, Integer> printInfo = (name, age) ->
System.out.println("Name: " + name + ", Age: " + age);
printInfo.accept("John", 25);
}
}
Both Consumer
and BiConsumer
are commonly used in functional programming scenarios, especially when working with collections and streams