Java-List集合字段求和函数
⽂章⽬录
⼀、FunctionCustom通⽤求和函数使⽤⽰例
特点:
简化代码量
防⽌集合及值的空指针
// 实例化函数
FunctionCustom<GetSalesDataReportsServiceOutputDto> functionCustom = new FunctionCustom<>();
//使⽤-》对 clueTodayCount 值求和
functionCustom.functionListLongSum(dtoEntityValue, en ->StringUtils.ClueTodayCount()),GetSalesDataReportsServiceOutputDto::getClue Toda
yCount)
⼆、求和函数
package com.bqx.bi.cluereport.util.functioncus;
llect.Lists;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
/**
* @author (kevin).
* @title bqx-bi.
* @package com.bqx.bi.cluereport.util.functioncus.
* @description ⾃定义函数.
* @date 2021/1/20.
*/
public class FunctionCustom<T> {
/**
* Long求和函数.
*
* @param targetList list
* @param predicate 过滤函数.
* @param function 求和函数.
* @return 求和值.
*/
public Long functionListLongSum(List<T> targetList, Predicate<? super T> predicate,
ToLongFunction<? super T> function) {
return Optional.ofNullable(targetList).wArrayList()).parallelStream().filter(predicate)
.mapToLong(function).sum();
}
/**
* int求和函数.
*
* @param targetList list
* @param predicate 过滤函数.
* @param function 求和函数.
* @return 求和值.
*/
public int functionListIntSum(List<T> targetList, Predicate<? super T> predicate, ToIntFunction<? super T> function) { return Optional.ofNullable(targetList).wArrayList()).parallelStream().filter(predicate)
.mapToInt(function).sum();
}
/**
* Double求和函数.
*
* @param targetList list
* @param predicate 过滤函数.
* @param function 求和函数.
* @return 求和值.
*/
public Double functionListDoubleSum(List<T> targetList, Predicate<? super T> predicate,
ToDoubleFunction<? super T> function) {
return Optional.ofNullable(targetList).wArrayList()).parallelStream().filter(predicate)
.mapToDouble(function).sum();
}
}