java8 Stream API之reduce使用說明
本篇我們只講reduce。
reduce的作用是把stream中的元素給組合起來。
至于怎么組合起來:它需要我們首先提供一個起始種子,然后依照某種運算規(guī)則使其與stream的第一個元素發(fā)生關系產(chǎn)生一個新的種子,這個新的種子再緊接著與stream的第二個元素發(fā)生關系產(chǎn)生又一個新的種子,就這樣依次遞歸執(zhí)行,最后產(chǎn)生的結果就是reduce的最終產(chǎn)出,這就是reduce的算法最通俗的描述;
那么結合實際的業(yè)務場景來說,運用reduce我們可以做sum,min,max,average,所以這些我們稱之為針對具體應用場景的reduce,這些常用的reduce,stream api已經(jīng)為我們封裝了對應的方法。
以下給出一些具體應用場景的reduce實現(xiàn)方式:
sum
@Test
public void testSum() {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
// 沒有起始值時返回為Optional類型
Optional<Integer> sumOptional = integers.stream().reduce(Integer::sum);
System.out.println(sumOptional.get());
// 可以給一個起始種子值
Integer sumReduce = integers.stream().reduce(0, Integer::sum);
System.out.println(sumReduce);
//直接用sum方法
Integer sum = integers.stream().mapToInt(i -> i).sum();
System.out.println(sum);
}
concat
@Test
public void testConcat() {
//構造字符串流
List<String> strs = Arrays.asList("H", "E", "L", "L", "O");
// reduce
String concatReduce = strs.stream().reduce("", String::concat);
System.out.println(concatReduce);
}
min
@Test
public void testMin() {
//min reduce
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
Integer minReduce = integerStream.reduce(Integer.MAX_VALUE, Integer::min);
System.out.println(minReduce);
// min
Stream<Integer> integerStream1 = Stream.of(1, 2, 3, 4, 5);
OptionalInt min = integerStream1.mapToInt(i -> i).min();
System.out.println(min.getAsInt());
}
max
@Test
public void testMax() {
//max reduce
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
Integer maxReduce = integerStream.reduce(Integer.MIN_VALUE, Integer::max);
System.out.println(maxReduce);
// max
Stream<Integer> integerStream1 = Stream.of(1, 2, 3, 4, 5);
OptionalInt max = integerStream1.mapToInt(i -> i).max();
System.out.println(max.getAsInt());
}
ok,相信大家已經(jīng)對reduce有所了解!
補充知識:了解Java JNI及動態(tài)鏈接庫
提到Java JNI不得不提到動態(tài)鏈接庫,在window操作系統(tǒng)中一般為后綴為DLL的文件,在Linux中為.so文件。動態(tài)鏈接庫的作用在于為多個應用程序提供相同的函數(shù)功能,以此達到節(jié)省代碼量,節(jié)省內存,共享相關數(shù)據(jù)、系統(tǒng)資源的作用。
Java的JNI則是為了對接這種功能的技術。
Java中的一個方法申明為native時,是不會直接用java代碼去做實現(xiàn)的,因為native方法就是通過JNI去調用動態(tài)庫。JDK中有很多native方法,通常涉及到一些底層技術,系統(tǒng)資源相關。
以上這篇java8 Stream API之reduce使用說明就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring Boot Admin管理監(jiān)控數(shù)據(jù)的方法
本篇文章主要介紹了Spring Boot Admin管理監(jiān)控數(shù)據(jù)的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12
Springboot+TCP監(jiān)聽服務器搭建過程圖解
這篇文章主要介紹了Springboot+TCP監(jiān)聽服務器搭建過程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10
MyBatis Mapper XML中比較操作符轉義問題解決
在使用MyBatis編寫Mapper XML時,有時會遇到比較操作符需要進行轉義的情況,本文主要介紹了MyBatis Mapper XML中比較操作符轉義問題解決,具有一定的參考價值,感興趣的可以了解一下2024-01-01

