How do I use the ObjIntConsumer functional interface in Java?

The ObjIntConsumer is a functional interface in Java, introduced in Java 8, as part of the java.util.function package. It represents an operation that takes an object (T) and an int as input arguments and returns no result. It’s essentially a BiConsumer that specifically takes an int as one of the parameters.

Here is a breakdown of how we can use the ObjIntConsumer interface:


Functional Interface Definition

@FunctionalInterface
public interface ObjIntConsumer<T> {
    void accept(T t, int value);
}

Key Features:

  1. The accept method is the only abstract method in this interface. It accepts two parameters:
    • T t (an object of any type)
    • int value (a primitive integer)
  2. Unlike BiConsumer<T, U>, this interface avoids boxing for the second parameter by working directly with a primitive int.

Example Usage:

1. Basic Example:

We can use ObjIntConsumer as a lambda expression or assign it to handle specific functionality.

package org.kodejava.util.function;

import java.util.function.ObjIntConsumer;

public class ObjIntConsumerExample {

   public static void main(String[] args) {
      // Create an ObjIntConsumer
      ObjIntConsumer<String> printNTimes = (str, count) -> {
         for (int i = 0; i < count; i++) {
            System.out.println(str);
         }
      };

      // Use the ObjIntConsumer
      printNTimes.accept("Hello, World!", 3);
   }
}

Output:

Hello, World!
Hello, World!
Hello, World!

2. Processing a List With Indices:

We can use it to perform an operation on a list, with the int parameter as the index.

package org.kodejava.util.function;

import java.util.List;
import java.util.function.ObjIntConsumer;

public class ObjIntConsumerWithListExample3 {

   public static void main(String[] args) {
      List<String> names = List.of("Alice", "Bob", "Charlie");

      // Create an ObjIntConsumer
      ObjIntConsumer<List<String>> printNameWithIndex = (list, index) ->
              System.out.println("Index: " + index + ", Name: " + list.get(index));

      // Apply the ObjIntConsumer on the list
      for (int i = 0; i < names.size(); i++) {
         printNameWithIndex.accept(names, i);
      }
   }
}

Output:

Index: 0, Name: Alice
Index: 1, Name: Bob
Index: 2, Name: Charlie

3. Using With Custom Objects:

We can apply ObjIntConsumer with custom objects. For instance:

package org.kodejava.util.function;

import java.util.function.ObjIntConsumer;

public class ObjIntConsumerCustomObjectExample4 {

   public static void main(String[] args) {
      Product product = new Product("Laptop", 1000);

      // Create an ObjIntConsumer
      ObjIntConsumer<Product> applyDiscount = (prod, discount) -> prod.applyDiscount(discount);

      // Apply a 15% discount
      applyDiscount.accept(product, 15);

      // Print updated product details
      System.out.println(product);
   }
}

class Product {
   private String name;
   private double price;

   public Product(String name, double price) {
      this.name = name;
      this.price = price;
   }

   public void applyDiscount(int percentage) {
      this.price -= (this.price * percentage / 100.0);
   }

   @Override
   public String toString() {
      return "Product{name='" + name + "', price=" + price + '}';
   }
}

Output:

Product{name='Laptop', price=850.0}

Key Use Cases

  1. Index-Based Operations: Applying operations that depend on both an object and an index or count.
  2. Side Effects: Performing actions like printing or logging inside lambdas.
  3. Custom Logic: Executing custom logic on objects with an additional int parameter, e.g., percentages, counters, etc.

The ObjIntConsumer is a lightweight and specialized functional interface that simplifies defining operations combining objects and primitive int parameters, without incurring boxing overhead!

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.