首页 文章资讯内容详情

Java中使用Lambda表达式实现IntBinaryOperator

2026-06-04 1 花语

IntBinaryOperator 是Java8中java.util.function包中的功能接口。该接口需要两个int类型的参数作为输入, 并产生一个int类型的结果。IntBinaryOperator可用作lambda表达式方法引用的分配目标。它仅包含一个抽象方法:applyAsInt()

语法

@FunctionalInterface public interface IntBinaryOperator { int applyAsInt(int left, int right) }

示例

import java.util.function.*; public class IntBinaryOperatorTest { public static void main(String[] args) { IntBinaryOperator test1 = (a, b) -> a + b; // lambda 表达式 System.out.println("两个参数相加: " + test1.applyAsInt(10, 20)); IntFunction test2 = new IntFunction() { @Override public IntBinaryOperator apply(int value) { return new IntBinaryOperator() { @Override public int applyAsInt(int left, int right) { return value * left * right; } }; } }; System.out.println("三个参数相乘: " + test2.apply(10).applyAsInt(20, 30)); } }

输出结果

两个参数相加: 30 三个参数相乘: 6000