Stream流求和

ashuai~發表於2024-07-16

Stream流對List<Object> 和 Set<Object>求和

泛型為Integer、Long、Double、BigDecimal的求和

  1. 使用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));
  1. 使用mapToInt + sum
ArrayList<Integer> list = new ArrayList<>();
Collections.addAll(list, 1, 2, 3);
System.out.println(list.stream().mapToInt(Integer::intValue).sum());

泛型為泛型為實體類

  1. 使用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);

參考:https://www.cnblogs.com/thsrite/p/17582745.html

相關文章