需求
對int,long類型的數據求和直接用stream().mapToInt()、stream().mapToDouble(),可是沒有stream().mapToBigDecimal()這樣的方法,那么如何用stream對List的BigDecimal字段進行求和?
代碼實現
直接上代碼
public class OrderInfo {private BigDecimal fee;
}public class ListTest2 {public static void main(String[] args) {OrderInfo orderInfo = new OrderInfo();orderInfo.setFee(new BigDecimal(10));OrderInfo orderInfo2 = new OrderInfo();orderInfo2.setFee(new BigDecimal(20));List<OrderInfo> list1 = new ArrayList<>();list1.add(orderInfo);list1.add(orderInfo2);BigDecimal ret = list1.stream().map(e -> e.getFee()).reduce(BigDecimal::add).get();System.out.println(ret.intValue());}
}
輸出結果是30。
語法說明
(1).stream()表示返回一個以本集合為數據源的順序流。
(2).map()表示對流中的每個元素執行?映射轉換?,生成新元素組成的新流。代碼中的意思是提取流中每個元素的fee屬性,將其映射為BigDecimal類型的流。
(3).reduce() 表示 Java Stream API 中的?終止操作?,其核心作用是將流中的元素合并為單個結果。代碼中的意思是使用BigDecimal的add方法進行歸約求和,返回Optional。
(4).get()?方法表示從Optional中獲取最終計算結果。