BigDecimal: BigDecimal bb =list.stream().map(Plan::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add); int、double、long: double max = list.stream().mapToDouble(User::getHeight).sum(); 补充:java8-Stream流之数值函数(求和、最大
BigDecimal:
BigDecimal bb =list.stream().map(Plan::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add);
int、double、long:
double max = list.stream().mapToDouble(User::getHeight).sum();
补充:java8-Stream流之数值函数(求和、最大值、最小值、平均值)
我就废话不多说了,大家还是直接看代码吧~
//todo stream流的使用 //todo filter:过滤操作;保留符合过滤条件的对象;这是一个中间操作;后面可以带最终操作 //todo mapToInt: 将数据根据double类型来处理; public static void main(String[] args) { List<SalesOrder> list = createSalesOrder(); //获取集合中城市为上海的数量 System.out.println("mapToInt获取和:"+list.stream().filter(s -> s.getConsigneeCity().equals("上海")) .mapToInt(SalesOrder::getCreateUserId).sum()); //利用stream流中的函数获取相关数值信息 IntSummaryStatistics summaryStatistics = list.stream().filter(s -> s.getConsigneeCity().equals("上海")) .mapToInt(SalesOrder::getCreateUserId).summaryStatistics(); System.out.println("summaryStatistics函数获取数量:"+summaryStatistics.getCount()); System.out.println("summaryStatistics函数获取平均值:"+summaryStatistics.getAverage()); System.out.println("summaryStatistics函数获取最大值:"+summaryStatistics.getMax()); System.out.println("summaryStatistics函数获取最小值:"+summaryStatistics.getMin()); System.out.println("summaryStatistics函数获取和"+summaryStatistics.getSum()); } static List<SalesOrder> createSalesOrder(){ List<SalesOrder> list = new LinkedList<>(); SalesOrder salesOrder = new SalesOrder(); salesOrder.setCreateUserId(12); salesOrder.setConsigneeCity("上海"); list.add(salesOrder); salesOrder = new SalesOrder(); salesOrder.setConsigneeCity("上海"); salesOrder.setCreateUserId(24); list.add(salesOrder); salesOrder = new SalesOrder(); salesOrder.setConsigneeCity("北京"); salesOrder.setCreateUserId(18); list.add(salesOrder); salesOrder = new SalesOrder(); salesOrder.setConsigneeCity("深圳"); salesOrder.setCreateUserId(16); list.add(salesOrder); salesOrder = new SalesOrder(); salesOrder.setConsigneeCity("广州"); salesOrder.setCreateUserId(30); list.add(salesOrder); salesOrder = new SalesOrder(); salesOrder.setConsigneeCity("杭州"); salesOrder.setCreateUserId(40); list.add(salesOrder); return list; }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持易盾网络。如有错误或未考虑完全的地方,望不吝赐教。