Java 中的 BiFunction 與 BinaryOperator使用示例
在 Java 8 引入的函數(shù)式編程特性中,BiFunction 和 BinaryOperator 是兩個(gè)非常重要的函數(shù)式接口,它們?cè)谔幚矶僮骱秃瘮?shù)組合時(shí)發(fā)揮著關(guān)鍵作用。下面將從基礎(chǔ)概念、核心區(qū)別、實(shí)際應(yīng)用等多個(gè)維度深入解析這兩個(gè)接口。
一、BiFunction 接口詳解
BiFunction 是 Java 函數(shù)式編程中處理二元輸入的基礎(chǔ)接口,它定義了接收兩個(gè)參數(shù)并返回一個(gè)結(jié)果的函數(shù)行為。
1. 基本定義與語(yǔ)法
@FunctionalInterface
public interface BiFunction<T, U, R> {
R apply(T t, U u);
}T:第一個(gè)輸入?yún)?shù)的類型U:第二個(gè)輸入?yún)?shù)的類型R:返回結(jié)果的類型apply方法:接收兩個(gè)參數(shù)并返回計(jì)算結(jié)果
2. 使用示例
// 示例1:簡(jiǎn)單的數(shù)值計(jì)算
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
System.out.println(add.apply(5, 3)); // 輸出:8
// 示例2:字符串拼接
BiFunction<String, String, String> concat = (str1, str2) -> str1 + str2;
System.out.println(concat.apply("Hello, ", "World!")); // 輸出:Hello, World!
// 示例3:對(duì)象屬性計(jì)算
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
// 創(chuàng)建Person對(duì)象的BiFunction
BiFunction<String, Integer, Person> personCreator = Person::new;
Person person = personCreator.apply("Alice", 30);
System.out.println(person); // 輸出:Person{name='Alice', age=30}3. 常用默認(rèn)方法
BiFunction 接口提供了兩個(gè)實(shí)用的默認(rèn)方法,用于函數(shù)組合:
andThen(Function<? super R, ? extends V> after):將當(dāng)前函數(shù)的結(jié)果作為另一個(gè)函數(shù)的輸入compose(Function<? super T, ? extends U> before):將另一個(gè)函數(shù)的結(jié)果作為當(dāng)前函數(shù)的第一個(gè)輸入
// andThen示例:先相加再乘以2 BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b; Function<Integer, Integer> doubleValue = x -> x * 2; BiFunction<Integer, Integer, Integer> addThenDouble = add.andThen(doubleValue); System.out.println(addThenDouble.apply(5, 3)); // 輸出:16 // compose示例:先將輸入乘以2再相加 Function<Integer, Integer> doubleFirst = x -> x * 2; BiFunction<Integer, Integer, Integer> doubleFirstThenAdd = add.compose(doubleFirst); System.out.println(doubleFirstThenAdd.apply(5, 3)); // 輸出:13(5*2 + 3 = 13)
二、BinaryOperator 接口詳解
BinaryOperator 是 BiFunction 的子接口,專門用于處理兩個(gè)相同類型輸入并返回相同類型結(jié)果的場(chǎng)景,也被稱為二元運(yùn)算符。
1. 基本定義與語(yǔ)法
@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T, T, T> {
// 繼承自BiFunction的apply方法
T apply(T t, T u);
// 靜態(tài)工廠方法
static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) {
// 實(shí)現(xiàn)略
}
static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) {
// 實(shí)現(xiàn)略
}
}- 輸入?yún)?shù)和返回值類型均為
T - 繼承自
BiFunction<T, T, T>,本質(zhì)上是特殊化的BiFunction
2. 使用示例
// 示例1:數(shù)值運(yùn)算
BinaryOperator<Integer> add = (a, b) -> a + b;
System.out.println(add.apply(5, 3)); // 輸出:8
// 示例2:字符串最長(zhǎng)拼接(返回較長(zhǎng)的字符串)
BinaryOperator<String> longestString = (str1, str2) ->
str1.length() > str2.length() ? str1 : str2;
System.out.println(longestString.apply("Hello", "World!")); // 輸出:World!
// 示例3:使用靜態(tài)工廠方法
List<Integer> numbers = Arrays.asList(10, 5, 8, 15, 3);
// 使用maxBy找到最大值
BinaryOperator<Integer> max = BinaryOperator.maxBy(Comparator.naturalOrder());
int result = numbers.stream()
.reduce(0, max); // 初始值為0,可能需要調(diào)整邏輯
System.out.println(result); // 輸出:153. 與 reduce 操作結(jié)合
BinaryOperator 最常見的應(yīng)用場(chǎng)景是與 Stream.reduce() 方法結(jié)合,用于聚合操作:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// 計(jì)算總和(使用Lambda表達(dá)式)
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
System.out.println("總和:" + sum); // 輸出:15
// 計(jì)算總和(使用BinaryOperator)
BinaryOperator<Integer> addOperator = Integer::sum;
int sum2 = numbers.stream()
.reduce(0, addOperator);
System.out.println("總和:" + sum2); // 輸出:15
// 尋找最大值
Integer max = numbers.stream()
.reduce(Integer::max)
.orElse(0);
System.out.println("最大值:" + max); // 輸出:5三、BiFunction 與 BinaryOperator 的核心區(qū)別
| 特性 | BiFunction<T, U, R> | BinaryOperator<T> |
|---|---|---|
| 參數(shù)類型 | 兩個(gè)不同類型的參數(shù)(T 和 U) | 兩個(gè)相同類型的參數(shù)(T 和 T) |
| 返回值類型 | 可以與參數(shù)類型不同(R) | 必須與參數(shù)類型相同(T) |
| 接口關(guān)系 | 基礎(chǔ)函數(shù)式接口 | 繼承自 BiFunction 的子接口 |
| 典型應(yīng)用場(chǎng)景 | 處理不同類型的輸入組合 | 處理相同類型的二元運(yùn)算(如聚合) |
| 靜態(tài)方法 | 無(wú) | 提供 minBy 和 maxBy 靜態(tài)工廠方法 |
示例對(duì)比:
- 當(dāng)需要計(jì)算
String和Integer的組合結(jié)果時(shí),必須使用BiFunction<String, Integer, ?> - 當(dāng)需要計(jì)算兩個(gè)
Double類型的最大值時(shí),使用BinaryOperator<Double>更合適
四、實(shí)際應(yīng)用場(chǎng)景
1. 數(shù)據(jù)轉(zhuǎn)換與映射
// 將兩個(gè)不同類型的數(shù)據(jù)轉(zhuǎn)換為新類型
BiFunction<String, Integer, Map<String, Object>> userMapper = (name, age) -> {
Map<String, Object> user = new HashMap<>();
user.put("name", name);
user.put("age", age);
return user;
};
Map<String, Object> user = userMapper.apply("Bob", 25);
System.out.println(user); // 輸出:{name=Bob, age=25}2. 集合聚合操作
List<String> words = Arrays.asList("Java", "is", "powerful");
// 使用BinaryOperator連接字符串
String result = words.stream()
.reduce("", (a, b) -> a + (a.isEmpty() ? "" : " ") + b);
System.out.println(result); // 輸出:Java is powerful
// 更簡(jiǎn)潔的寫法
String result2 = words.stream()
.reduce("", String::concat);
System.out.println(result2); // 輸出:Javaispowerful(無(wú)空格)3. 函數(shù)式編程中的組合模式
// 定義多個(gè)BiFunction并組合使用 BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b; BiFunction<Integer, Integer, Integer> multiply = (a, b) -> a * b; // 先相加再相乘:(a + b) * c BiFunction<Integer, Integer, Integer> addThenMultiply = add.andThen(b -> multiply.apply(b, 2)); System.out.println(addThenMultiply.apply(3, 4)); // 輸出:14((3+4)*2=14)
4. 自定義對(duì)象操作
class Product {
private String name;
private double price;
private int quantity;
// 構(gòu)造器、getter和setter略
@Override
public String toString() {
return "Product{" +
"name='" + name + "', " +
"price=" + price + ", " +
"quantity=" + quantity +
'}';
}
}
// 計(jì)算產(chǎn)品總價(jià)值的BinaryOperator
BinaryOperator<Product> calculateTotalValue = (p1, p2) -> {
double totalPrice = p1.getPrice() * p1.getQuantity() + p2.getPrice() * p2.getQuantity();
return new Product("Total", totalPrice, 1); // 簡(jiǎn)化處理
};
Product product1 = new Product("Laptop", 899.99, 2);
Product product2 = new Product("Phone", 599.99, 3);
Product total = calculateTotalValue.apply(product1, product2);
System.out.println(total); // 輸出總價(jià)值計(jì)算結(jié)果五、總結(jié)與最佳實(shí)踐
- 選擇原則:
- 當(dāng)兩個(gè)輸入?yún)?shù)類型不同或返回值類型與參數(shù)不同時(shí),使用
BiFunction - 當(dāng)兩個(gè)輸入?yún)?shù)類型相同且返回值類型與參數(shù)相同時(shí),優(yōu)先使用
BinaryOperator
- 當(dāng)兩個(gè)輸入?yún)?shù)類型不同或返回值類型與參數(shù)不同時(shí),使用
- 函數(shù)組合:
- 利用
andThen和compose方法實(shí)現(xiàn)復(fù)雜邏輯的組合,避免嵌套 Lambda 表達(dá)式
- 利用
- 與 Stream API 結(jié)合:
- 在
reduce、collect等聚合操作中,BinaryOperator是理想的參數(shù)選擇
- 在
- 靜態(tài)工廠方法:
BinaryOperator提供的minBy和maxBy方法可簡(jiǎn)化比較操作的實(shí)現(xiàn)
通過(guò)熟練掌握 BiFunction 和 BinaryOperator,開發(fā)者可以更高效地編寫函數(shù)式代碼,提升代碼的可讀性和簡(jiǎn)潔性,同時(shí)充分發(fā)揮 Java 8 + 函數(shù)式編程的優(yōu)勢(shì)。在實(shí)際項(xiàng)目中,合理運(yùn)用這些接口能夠有效減少樣板代碼,使邏輯更加清晰直觀。
到此這篇關(guān)于Java 中的 BiFunction 與 BinaryOperator使用示例的文章就介紹到這了,更多相關(guān)java bifunction 與 binaryoperator內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MyBatis-Plus 查詢返回實(shí)體對(duì)象還是map
這篇文章主要介紹了MyBatis-Plus 查詢返回實(shí)體對(duì)象還是map,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
通過(guò)反射實(shí)現(xiàn)Java下的委托機(jī)制代碼詳解
這篇文章主要介紹了通過(guò)反射實(shí)現(xiàn)Java下的委托機(jī)制代碼詳解,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12
Mybatis一對(duì)一延遲加載實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了Mybatis一對(duì)一延遲加載實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
spring boot 使用@Async實(shí)現(xiàn)異步調(diào)用方法
本篇文章主要介紹了spring boot 使用@Async實(shí)現(xiàn)異步調(diào)用方法,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-04-04
在ssm中使用ModelAndView跳轉(zhuǎn)頁(yè)面失效的解決
這篇文章主要介紹了在ssm中使用ModelAndView跳轉(zhuǎn)頁(yè)面失效的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
SpringBoot如何使用validator框架優(yōu)雅地校驗(yàn)參數(shù)
文章介紹了如何使用SpringValidation進(jìn)行參數(shù)校驗(yàn),包括引入依賴、@requestBody和@requestParam參數(shù)校驗(yàn)、統(tǒng)一異常處理、分組校驗(yàn)、嵌套校驗(yàn)、自定義校驗(yàn)、業(yè)務(wù)規(guī)則校驗(yàn)以及@Valid和@Validated的區(qū)別,同時(shí),列舉了常用的BeanValidation和HibernateValidator注解2025-02-02
Mybatis分頁(yè)插件PageHelper手寫實(shí)現(xiàn)示例
這篇文章主要為大家介紹了Mybatis分頁(yè)插件PageHelper手寫實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08

