Java8函數(shù)式接口UnaryOperator用法示例
Java 8函數(shù)式接口UnaryOperator<T>
UnaryOperator<T> 是 Java 8 中的一個函數(shù)式接口,是 Function<T, T> 的子接口。它表示接受一個輸入?yún)?shù)和返回值都是相同類型 T 的操作。
UnaryOperator<T> 接口用法示例
import java.util.function.UnaryOperator;
public class UnaryOperatorExample {
public static void main(String[] args) {
// 示例1:對整數(shù)進行平方運算
UnaryOperator<Integer> square = num -> num * num;
int result = square.apply(5);
System.out.println(result); // 輸出: 25
// 示例2:添加感嘆號到字符串末尾
UnaryOperator<String> addExclamation = str -> str + "!";
String text = addExclamation.apply("Hello");
System.out.println(text); // 輸出: Hello!
// 示例3:組合多個函數(shù)
UnaryOperator<Integer> incrementAndSquare = num -> num + 1;
incrementAndSquare = incrementAndSquare.andThen(square);
result = incrementAndSquare.apply(5);
System.out.println(result); // 輸出: 36
}
}在示例1中,我們創(chuàng)建了一個 UnaryOperator<Integer> 對象 square,用于對整數(shù)進行平方運算。通過調(diào)用 apply 方法,并將數(shù)字 5 作為參數(shù)傳入,我們可以得到結(jié)果 25。
在示例2中,我們創(chuàng)建了一個 UnaryOperator<String> 對象 addExclamation,用于在字符串末尾添加感嘆號。通過調(diào)用 apply 方法,并將字符串 "Hello" 作為參數(shù)傳入,我們可以得到結(jié)果 "Hello!"。
在示例3中,我們將兩個函數(shù) incrementAndSquare 和 square 進行組合。
首先將傳入的整數(shù)加1,然后對結(jié)果進行平方運算。通過調(diào)用 andThen 方法,我們可以得到一個新的 UnaryOperator 對象 incrementAndSquare,它將傳入的整數(shù)加1并對結(jié)果進行平方運算。最終,通過調(diào)用 apply 方法,并將數(shù)字 5 作為參數(shù)傳入,我們可以得到結(jié)果 36。
以上就是Java8函數(shù)式接口UnaryOperator用法示例的詳細(xì)內(nèi)容,更多關(guān)于Java8函數(shù)式接口UnaryOperator的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
java中處理json各種各樣的轉(zhuǎn)換方法(推薦)
下面小編就為大家分享一篇java中處理json各種各樣的轉(zhuǎn)換方法小結(jié),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-11-11
mybatis攔截器實現(xiàn)通用權(quán)限字段添加的方法
這篇文章主要給大家介紹了關(guān)于mybatis攔截器實現(xiàn)通用權(quán)限字段添加的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用mybatis具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
Spring Boot 中application.yml與bootstrap.yml的區(qū)別
其實yml和properties文件是一樣的原理,且一個項目上要么yml或者properties,二選一的存在。這篇文章給大家介紹了Spring Boot 中application.yml與bootstrap.yml的區(qū)別,感興趣的朋友一起看看吧2018-04-04
SpringBoot JPA懶加載失效的解決方案(親測有效)
這篇文章主要介紹了SpringBoot JPA懶加載失效的解決方案(親測有效),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08

