ZetCode

Java ObjIntConsumer 接口

最后修改时间:2025 年 4 月 16 日

java.util.function.ObjIntConsumer 接口表示一个操作,该操作接受一个对象值和一个 int 值参数,并且不返回任何结果。它是一个函数式接口,具有单个抽象方法 accept

ObjIntConsumer 是 Java 8 中添加的 Java 函数式编程实用程序的一部分。当您需要执行组合对象和基本 int 值的操作时,它会被使用。与常规消费者不同,它避免了自动装箱的开销。

ObjIntConsumer 接口概述

ObjIntConsumer 接口包含一个必须实现的抽象方法。该方法对给定的对象和 int 参数执行操作。此接口中没有默认方法或静态方法。

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

上面的代码显示了 ObjIntConsumer 接口的结构。它使用泛型,其中 T 是对象参数的类型。该接口使用 @FunctionalInterface 进行注释,以指示其单个抽象方法的性质。

ObjIntConsumer 的基本用法

使用 ObjIntConsumer 的最简单方法是使用 lambda 表达式。我们定义了如何处理对象和 int 参数。示例显示了一个消费者,它打印两个值。

Main.java
package com.zetcode;

import java.util.function.ObjIntConsumer;

public class Main {

    public static void main(String[] args) {

        // Define a consumer that prints object and int
        ObjIntConsumer<String> printCombined = (s, i) -> 
            System.out.println("String: " + s + ", int: " + i);
        
        // Use the consumer
        printCombined.accept("Hello", 42);
        printCombined.accept("Java", 8);
        
        // Consumer with more complex logic
        ObjIntConsumer<String> repeatPrint = (str, count) -> {
            for (int i = 0; i < count; i++) {
                System.out.println(str);
            }
        };
        
        repeatPrint.accept("Loop", 3);
    }
}

此示例演示了使用 lambda 表达式的基本 ObjIntConsumer 用法。 printCombined 消费者只是简单地打印两个参数。 repeatPrint 消费者显示了更复杂的逻辑,根据 int 值多次打印一个字符串。

将 ObjIntConsumer 与集合一起使用

当您需要将元素与其索引或其他整数值组合时,ObjIntConsumer 可能会很有用。此示例演示了如何将其与列表一起使用。

Main.java
package com.zetcode;

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

public class Main {

    public static void main(String[] args) {

        List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
        
        // Consumer to print name with index
        ObjIntConsumer<String> printIndexed = (name, index) ->
            System.out.println((index + 1) + ". " + name);
        
        // Process list with index
        for (int i = 0; i < names.size(); i++) {
            printIndexed.accept(names.get(i), i);
        }
        
        // Consumer to build a formatted string
        StringBuilder sb = new StringBuilder();
        ObjIntConsumer<String> buildString = (s, i) -> {
            if (i > 0) sb.append(", ");
            sb.append(s).append(":").append(i);
        };
        
        for (int i = 0; i < names.size(); i++) {
            buildString.accept(names.get(i), i);
        }
        
        System.out.println("Formatted: " + sb.toString());
    }
}

此示例显示了将 ObjIntConsumer 与名称列表一起使用。 printIndexed 消费者显示每个名称及其基于 1 的索引。 buildString 消费者创建一个格式化的字符串,将名称与其索引组合在一起。

ObjIntConsumer 在对象处理中的应用

当处理与整数值有一定关系的对象时,ObjIntConsumer 特别有用。此示例演示了更新购物车中的产品数量。

Main.java
package com.zetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.function.ObjIntConsumer;

class Product {
    String name;
    double price;
    
    Product(String name, double price) {
        this.name = name;
        this.price = price;
    }
    
    @Override
    public String toString() {
        return name + " ($" + price + ")";
    }
}

public class Main {

    public static void main(String[] args) {

        Map<Product, Integer> cart = new HashMap<>();
        cart.put(new Product("Laptop", 999.99), 1);
        cart.put(new Product("Mouse", 25.50), 2);
        cart.put(new Product("Keyboard", 45.75), 1);
        
        // Consumer to update product quantities
        ObjIntConsumer<Product> updateQuantity = (product, quantity) -> {
            int current = cart.getOrDefault(product, 0);
            cart.put(product, current + quantity);
        };
        
        // Add more items to cart
        Product mouse = new Product("Mouse", 25.50);
        updateQuantity.accept(mouse, 3);
        
        Product headphones = new Product("Headphones", 79.99);
        updateQuantity.accept(headphones, 2);
        
        // Print final cart contents
        ObjIntConsumer<Product> printCartItem = (p, q) ->
            System.out.println(p + " x " + q + " = $" + (p.price * q));
        
        cart.forEach((k, v) -> printCartItem.accept(k, v));
    }
}

此示例显示了将 ObjIntConsumer 用于购物车操作。 updateQuantity 消费者将指定数量添加到购物车中的产品。 printCartItem 消费者显示每个产品及其数量和总价。这演示了实用的对象-int 对处理。

将 ObjIntConsumer 与其他函数式接口结合使用

ObjIntConsumer 可以与其他函数式接口结合使用,以创建更复杂的操作。此示例展示了与 Predicate 和 Function 的集成。

Main.java
package com.zetcode;

import java.util.function.Function;
import java.util.function.ObjIntConsumer;
import java.util.function.Predicate;

public class Main {

    public static void main(String[] args) {

        // Function to create greeting
        Function<String, String> greeter = name -> "Hello, " + name + "!";
        
        // Predicate to check if number is even
        Predicate<Integer> isEven = n -> n % 2 == 0;
        
        // Consumer that combines both
        ObjIntConsumer<String> complexConsumer = (name, number) -> {
            String greeting = greeter.apply(name);
            String evenOdd = isEven.test(number) ? "even" : "odd";
            System.out.println(greeting + " Your number is " + number + 
                " which is " + evenOdd + ".");
        };
        
        // Use the combined consumer
        complexConsumer.accept("Alice", 42);
        complexConsumer.accept("Bob", 7);
        
        // Another example with calculation
        ObjIntConsumer<Double> powerCalculator = (base, exponent) -> {
            double result = Math.pow(base, exponent);
            System.out.printf("%.2f^%d = %.2f%n", base, exponent, result);
        };
        
        powerCalculator.accept(2.5, 3);
        powerCalculator.accept(10.0, -2);
    }
}

此示例演示了将 ObjIntConsumer 与其他函数式接口结合使用。 complexConsumer 使用 Function 和 Predicate 创建更复杂的操作。 powerCalculator 显示了结合 double 和 int 值的数学运算。

ObjIntConsumer 在流处理中的应用

虽然 ObjIntConsumer 未在 Stream API 方法中直接使用,但它可以在您需要处理对象-int 对的流处理场景中提供帮助。此示例显示了自定义的类似流的操作。

Main.java
package com.zetcode;

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

public class Main {

    static <T> void processWithIndices(List<T> list, ObjIntConsumer<T> consumer) {
        for (int i = 0; i < list.size(); i++) {
            consumer.accept(list.get(i), i);
        }
    }

    public static void main(String[] args) {

        List<String> colors = Arrays.asList("Red", "Green", "Blue", "Yellow");
        
        // Consumer to create indexed color codes
        ObjIntConsumer<String> colorCoder = (color, index) -> {
            String code = color.substring(0, 3).toUpperCase() + index;
            System.out.println(color + " -> " + code);
        };
        
        processWithIndices(colors, colorCoder);
        
        // Another example with statistics
        int[] totals = new int[1];
        ObjIntConsumer<Integer> summer = (num, weight) -> {
            totals[0] += num * weight;
        };
        
        List<Integer> numbers = Arrays.asList(10, 20, 30, 40);
        processWithIndices(numbers, summer);
        System.out.println("Weighted total: " + totals[0]);
    }
}

此示例显示了使用 ObjIntConsumer 的自定义流处理方法。 processWithIndices 方法将消费者应用于每个元素及其索引。 colorCoder 创建结合颜色名称和位置的代码。 summer 计算数字的加权总和。

ObjIntConsumer 用于配置

ObjIntConsumer 适用于配置场景,其中需要使用整数参数配置对象。此示例显示了设置应用程序模式。

Main.java
package com.zetcode;

import java.util.function.ObjIntConsumer;

class Device {
    String name;
    int brightness;
    int volume;
    
    Device(String name) {
        this.name = name;
    }
    
    void displaySettings() {
        System.out.printf("%s - Brightness: %d, Volume: %d%n", 
            name, brightness, volume);
    }
}

public class Main {

    public static void main(String[] args) {

        Device tv = new Device("Living Room TV");
        Device speaker = new Device("Kitchen Speaker");
        
        // Consumers for different device settings
        ObjIntConsumer<Device> setBrightness = (d, b) -> {
            d.brightness = Math.min(Math.max(b, 0), 100);
        };
        
        ObjIntConsumer<Device> setVolume = (d, v) -> {
            d.volume = Math.min(Math.max(v, 0), 50);
        };
        
        // Apply settings
        setBrightness.accept(tv, 75);
        setVolume.accept(tv, 30);
        
        setBrightness.accept(speaker, 0); // No brightness control
        setVolume.accept(speaker, 25);
        
        // Show final settings
        tv.displaySettings();
        speaker.displaySettings();
        
        // Consumer with validation
        ObjIntConsumer<Device> safeVolume = (d, v) -> {
            if (d.name.contains("Speaker") && v > 40) {
                System.out.println("Warning: High volume for speaker!");
            }
            setVolume.accept(d, v);
        };
        
        safeVolume.accept(speaker, 45);
        speaker.displaySettings();
    }
}

此示例演示了将 ObjIntConsumer 用于设备配置。不同的消费者处理亮度和音量设置以及适当的约束。 safeVolume 消费者添加了特定于扬声器设备的验证逻辑。这展示了 ObjIntConsumer 如何封装设置逻辑。

来源

Java ObjIntConsumer 接口文档

在本文中,我们介绍了 Java ObjIntConsumer 接口的基本方法和特性。理解这些概念对于需要将对象与基本 int 值组合处理的场景非常有价值。

作者

我的名字是 Jan Bodnar,我是一位经验丰富的程序员,在该领域拥有多年的经验。我从 2007 年开始撰写编程文章,至今已撰写了 1,400 多篇文章和 8 本电子书。凭借超过八年的教学经验,我致力于分享我的知识并帮助他人掌握编程概念。

列出所有Java教程