Java 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; }
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。
推薦閱讀:
- Java基礎之Stream流原理與用法詳解
- Java BigDecimal類用法詳解
- java8新特性之stream流中reduce()求和知識總結
- Java精確計算BigDecimal類詳解
- Java8新特性之Stream API詳解