The ObjIntConsumer interface is a functional interface from the java.util.function package, introduced in Java 8. It represents an operation that accepts an object and a primitive int value as arguments and does not return any result.
- The first argument is an object of generic type T, while the second argument is a primitive int.
- Its single abstract method is accept(T t, int value), which makes it suitable for lambda expressions and method references.
Syntax
@FunctionalInterface
public interface ObjIntConsumer<T> {
void accept(T t, int value);
}
Here, T represents the type of the object passed as the first argument. The second argument is always a primitive int.
Method of ObjIntConsumer
The ObjIntConsumer interface provides one abstract method, accept(), which performs an operation using the supplied object and int value.
accept()
The accept() method accepts an object of type T and a primitive int value. It performs the specified operation using these arguments without returning a value.
Syntax:
void accept(T t, int value)
Parameters:
- t: The input object of type T.
- value: The primitive int value supplied to the operation.
Return Type: The method does not return any value (void).
import java.util.Arrays;
import java.util.List;
import java.util.function.ObjIntConsumer;
public class GFG {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(3, 2, 5, 7, 4);
ObjIntConsumer<List<Integer>> operation =
(list, value) -> {
for (int number : list) {
System.out.println(number * value);
}
};
operation.accept(numbers, 2);
}
}
Output
6 4 10 14 8
Explanation: In the above example, the lambda expression provides the implementation of the accept() method. It receives a List<Integer> and the primitive int value 2. The lambda iterates through the list, multiplies each element by 2, and prints the resulting values. Since ObjIntConsumer represents a consumer operation, it does not return a result.
ObjIntConsumer vs BiConsumer
Both ObjIntConsumer and BiConsumer represent operations that accept two arguments and return no result. The main difference is the type of the second argument.
| Feature | ObjIntConsumer<T> | BiConsumer<T, U> |
|---|---|---|
| First argument | Reference type T | Reference type T |
| Second argument | Primitive int | Reference type U |
| Return type | void | void |
| Functional method | accept(T, int) | accept(T, U) |
| Primitive specialization | Yes | No |
Note: ObjIntConsumer<T> avoids boxing the primitive int into an Integer object, unlike BiConsumer<T, Integer>.
When to Use ObjIntConsumer?
Use ObjIntConsumer when an operation needs an object and a primitive int as inputs but does not need to produce a result. It is particularly useful when working with primitive int values because it avoids unnecessary boxing and unboxing.