计算一个number类型的List对象总和

Integer[] integerArray = {1, 3, 5, 10, 18};

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());

计算一个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);
User user3 = new User();
user3.setAge(25);
userList.add(user3);

int ageSum = userList.stream().collect(Collectors.summingInt(User::getAge));
System.out.println("年龄总和 :" + ageSum);
//下面一位网友提供了一种更加简洁的方式,非常感谢
int ageSumTwo = userList.stream().mapToInt(User::getAge).sum();
System.out.println("年龄总和2: " + ageSumTwo);

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐