Java ToIntBiFunction 接口
最后修改时间:2025 年 4 月 16 日
java.util.function.ToIntBiFunction
接口表示一个接受两个参数并产生一个 int 值结果的函数。它是一个函数式接口,具有一个抽象方法 applyAsInt
。
ToIntBiFunction
是 Java 8 中添加的 Java 函数式编程实用程序的一部分。它经过专门设计,用于在处理基本 int 类型时避免装箱。该接口对于将两个值组合成一个 int 值的操作非常有用。
ToIntBiFunction 接口概述
ToIntBiFunction
接口包含一个必须实现的抽象方法。该方法接受指定类型的两个参数,并返回一个基本 int 值。
@FunctionalInterface public interface ToIntBiFunction<T, U> { int applyAsInt(T t, U u); }
上面的代码显示了 ToIntBiFunction
的结构。它使用泛型,其中 T 和 U 是输入类型。该接口使用 @FunctionalInterface 注解,以表明其只有一个抽象方法。
基本 ToIntBiFunction 用法
使用 ToIntBiFunction 的最简单方法是使用 lambda 表达式。我们定义了如何将两个输入组合成一个 int 结果。该示例计算字符串长度差异。
package com.zetcode; import java.util.function.ToIntBiFunction; public class Main { public static void main(String[] args) { // Define function to calculate length difference ToIntBiFunction<String, String> lengthDiff = (s1, s2) -> s1.length() - s2.length(); // Apply the function System.out.println("Difference: " + lengthDiff.applyAsInt("hello", "world")); System.out.println("Difference: " + lengthDiff.applyAsInt("longer", "short")); } }
此示例演示了基本的 ToIntBiFunction 用法。lengthDiff 函数接受两个字符串,并返回它们长度的差值作为 int。我们使用 applyAsInt 方法将它应用于不同的字符串对。
计算数字的乘积
ToIntBiFunction 可以在其输入上执行数学运算。此示例显示了两个数字的乘法,演示了基本类型特化。
package com.zetcode; import java.util.function.ToIntBiFunction; public class Main { public static void main(String[] args) { // Multiply two integers ToIntBiFunction<Integer, Integer> multiplier = (a, b) -> a * b; System.out.println("Product: " + multiplier.applyAsInt(5, 7)); System.out.println("Product: " + multiplier.applyAsInt(12, 3)); // Using method reference with parseInt ToIntBiFunction<String, String> sumStrings = (s1, s2) -> Integer.parseInt(s1) + Integer.parseInt(s2); System.out.println("Sum: " + sumStrings.applyAsInt("10", "20")); } }
此示例显示了使用 ToIntBiFunction 的数学运算。multiplier 函数返回两个整数的乘积。sumStrings 函数在将字符串相加之前将字符串解析为整数,展示了类型转换。
使用 ToIntBiFunction 比较对象
ToIntBiFunction 可以实现对象之间的比较逻辑。这对于自定义排序或相等性检查很有用。示例按年龄比较 Person 对象。
package com.zetcode; import java.util.function.ToIntBiFunction; class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } } public class Main { public static void main(String[] args) { // Compare ages of two Person objects ToIntBiFunction<Person, Person> ageComparator = (p1, p2) -> p1.age - p2.age; Person alice = new Person("Alice", 30); Person bob = new Person("Bob", 25); System.out.println("Age difference: " + ageComparator.applyAsInt(alice, bob)); // Using in sorting Person[] people = {alice, bob, new Person("Charlie", 20)}; java.util.Arrays.sort(people, (p1, p2) -> ageComparator.applyAsInt(p1, p2)); System.out.println("Sorted by age: " + java.util.Arrays.toString(people)); } }
此示例演示了对象比较。ageComparator 函数返回两个 Person 对象之间的年龄差异。我们直接使用它,并在排序操作中使用它,展示了实际应用。
使用 ToIntBiFunction 的字符串操作
ToIntBiFunction 可以执行各种字符串操作。此示例计算两个字符串之间的公共字符,显示更复杂的逻辑。
package com.zetcode; import java.util.function.ToIntBiFunction; public class Main { public static void main(String[] args) { // Count common characters between two strings ToIntBiFunction<String, String> commonChars = (s1, s2) -> { int count = 0; for (char c : s1.toCharArray()) { if (s2.indexOf(c) != -1) { count++; } } return count; }; System.out.println("Common chars: " + commonChars.applyAsInt("hello", "world")); System.out.println("Common chars: " + commonChars.applyAsInt("apple", "pear")); } }
此示例显示了一个更复杂的 ToIntBiFunction 实现。commonChars 函数遍历第一个字符串的字符,并计算第二个字符串中的匹配项。结果是公共字符的计数。
将 ToIntBiFunction 与集合一起使用
ToIntBiFunction 可以处理集合。此示例计算两个列表中相应人员之间的总年龄差异。
package com.zetcode; import java.util.function.ToIntBiFunction; import java.util.List; public class Main { public static void main(String[] args) { List<Integer> list1 = List.of(10, 20, 30); List<Integer> list2 = List.of(5, 15, 25); // Sum of element-wise differences ToIntBiFunction<List<Integer>, List<Integer>> sumDiffs = (l1, l2) -> { int sum = 0; for (int i = 0; i < Math.min(l1.size(), l2.size()); i++) { sum += l1.get(i) - l2.get(i); } return sum; }; System.out.println("Total difference: " + sumDiffs.applyAsInt(list1, list2)); // Using with custom objects record Point(int x, int y) {} ToIntBiFunction<Point, Point> distanceSquared = (p1, p2) -> (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y); System.out.println("Distance squared: " + distanceSquared.applyAsInt(new Point(0, 0), new Point(3, 4))); } }
此示例使用 ToIntBiFunction 处理集合。sumDiffs 函数计算相应列表元素之间的总差值。distanceSquared 函数显示了使用自定义对象的数学计算。
将 ToIntBiFunction 与其他函数式接口结合使用
ToIntBiFunction 可以与其他函数式接口结合使用以进行更复杂的操作。此示例显示了与 Predicate 的组合。
package com.zetcode; import java.util.function.ToIntBiFunction; import java.util.function.Predicate; public class Main { public static void main(String[] args) { // Function to count matches based on predicate ToIntBiFunction<List<String>, Predicate<String>> countMatches = (list, predicate) -> { int count = 0; for (String s : list) { if (predicate.test(s)) { count++; } } return count; }; List<String> words = List.of("apple", "banana", "cherry", "date"); System.out.println("Count of a's: " + countMatches.applyAsInt(words, s -> s.startsWith("a"))); System.out.println("Count long words: " + countMatches.applyAsInt(words, s -> s.length() > 5)); } }
此示例将 ToIntBiFunction 与 Predicate 结合使用。countMatches 函数接受一个列表和一个谓词,返回满足条件的元素的计数。这展示了函数式接口如何协同工作以提供灵活的解决方案。
真实世界的例子:员工分析
ToIntBiFunction 可以解决现实世界中的业务问题。此示例分析员工数据,根据绩效和任职时间计算奖金点数。
package com.zetcode; import java.util.function.ToIntBiFunction; record Employee(String name, int performanceScore, int yearsOfService) {} public class Main { public static void main(String[] args) { // Calculate bonus points for employees ToIntBiFunction<Employee, Integer> bonusCalculator = (emp, basePoints) -> { int performanceMultiplier = emp.performanceScore() / 10; int tenureBonus = emp.yearsOfService() * 5; return basePoints * performanceMultiplier + tenureBonus; }; Employee emp1 = new Employee("Alice", 85, 3); Employee emp2 = new Employee("Bob", 92, 7); System.out.println("Alice's bonus: " + bonusCalculator.applyAsInt(emp1, 100)); System.out.println("Bob's bonus: " + bonusCalculator.applyAsInt(emp2, 100)); // Using with stream var employees = List.of(emp1, emp2); int totalBonus = employees.stream() .mapToInt(emp -> bonusCalculator.applyAsInt(emp, 100)) .sum(); System.out.println("Total bonus pool: " + totalBonus); } }
此实际示例展示了 ToIntBiFunction 在业务环境中的应用。bonusCalculator 根据多个因素计算员工奖金。我们还演示了使用流来处理员工集合。
来源
在本文中,我们介绍了 Java ToIntBiFunction 接口的基本方法和特性。理解这些概念对于使用 Java 中的双参数操作返回基本 int 值的函数式编程至关重要。
作者
列出所有Java教程。