Stream流对List<Object> 和 Set<Object>
求和
泛型为Integer、Long、Double、BigDecimal的求和
- 使用reduce + orElse
Integer sum = scores.stream().reduce(Integer::sum).orElse(0);
Long sum = scores.stream().reduce(Long::sum).orElse(0L);
Double sum = scores.stream().reduce(Double::sum).orElse(0.00);
BigDecimal sum = scores.stream().reduce(BigDecimal::add).orElse(new
BigDecimal(0.00));
- 使用mapToInt + sum
ArrayList<Integer> list = new ArrayList<>();
Collections.addAll(list, 1, 2, 3);
System.out.println(list.stream().mapToInt(Integer::intValue).sum());
泛型为泛型为实体类
- 使用mapToInt + sum
Integer sum = sales.stream().mapToInt(Sale::getOrderNum).sum();
Long sum = sales.stream().mapToLong(Sale::getOrderNum).sum();
Double sum = sales.stream().mapToDouble(Sale::getOrderNum).sum();
BigDecimal sum = sales.stream().map(Sale::getAppleSale).reduce(BigDecimal.ZERO,
BigDecimal::add);
标签:Stream,stream,求和,sum,reduce,Integer,orElse,BigDecimal From: https://www.cnblogs.com/ashuai123/p/18306247