什么是reduce操作
聚合操作,中⽂意思是 “減少”
根據⼀定的規則將Stream中的元素進⾏計算后返回⼀個
唯⼀的值
常⽤⽅法⼀:
Optional<T> reduce(BinaryOperator<T> accumulator);
accumulator 計算的累加器
例⼦: 第⼀個元素相加和第⼆個元素相加,結果再和第三個元素相加,直到全部相加完成
int value = Stream.of(1, 2, 3, 4, 5).reduce((item1, item2) -> item1+ item2).get();
常⽤⽅法⼆:
T reduce(T identity, BinaryOperator<T> accumulator);
identity ⽤戶提供⼀個循環計算的初始值
accumulator 計算的累加器
例⼦: 100作為初始值,然后和第⼀個元素相加,結果在和第⼆個元素相加,直到全部相加完成
int value = Stream.of(1, 2, 3, 4,5).reduce(100, (sum, item) -> sum +item);
練習 : 求最⼤值
int value = Stream.of(1645, 234345, 32,44434,564534,435,34343542,212)
.reduce( (item1, item2) -> item1 > item2 ? item1 : item2 ).get();