//1.对int类型list进行求和
Integer[] integerArray = {1, 2, 3, 4, 5, 10, 18, 20};
List<Integer> list = new ArrayList<>(Arrays.asList(integerArray));
IntSummaryStatistics summaryStatistics = list.stream().mapToInt((s) -> s).summaryStatistics();
System.out.println("-总和:" + summaryStatistics.getSum());
System.out.println("-平均数:" + summaryStatistics.getAverage());
System.out.println("--总个数:" + summaryStatistics.getCount());
System.out.println("-最大值:" + summaryStatistics.getMax());
System.out.println("-最小值:" + summaryStatistics.getMin());
//2.对list中的对象某个数值字段求和
List<User> userList = new ArrayList<>();
User user1 = new User();
user1.setAge(10);
userList.add(user1);
User user2 = new User();
user2.setAge(20);
userList.add(user2);
//写法1
int ageSum = userList.stream().collect(Collectors.summingInt(User::getAge));
System.out.println("年龄总和 :" + ageSum);
//写法2
int ageSumTwo = userList.stream().mapToInt(User::getAge).sum();
System.out.println("年龄总和2: " + ageSumTwo);
//3.对list中对象某个BigDecimal字段求和
List<Lpn> lpnList = service.selectInvGroupBId(containerId());
BigDecimal totalSku =
lpnList.stream().map(Lpn::getQty).reduce(BigDecimal.ZERO,BigDecimal::add);
java8使用stream对集合进行求和,平均数,最大最小值方法
最新推荐文章于 2024-09-29 15:45:59 发布