当前位置: 首页 > 图灵资讯 > 技术篇> Java求和元素_实现一个List集合中的某个元素的求和

Java求和元素_实现一个List集合中的某个元素的求和

来源:图灵教育
时间:2023-06-27 15:03:33

List userlist = userService.findAll();Integer sum= userlist .stream().collect(Collectors.summingInt(User::getAge));package com.example.list_test;import java.util.ArrayList;import java.util.List;/*** 描述:Listest3** @author 何志鹏* @ClassName:Listest3* @create 2019-05-30 18:49* Version 1.0*/public class Listest3 {undefinedpublic static void main(String[] args) {undefinedList list = new ArrayList<>();Student s1 = new Student();s1.setId(1);s1.setName(张三);s1.setAge(28);Student s2 = new Student();s2.setId(2);s2.setName(李四);s2.setAge(29);Student s3 = new Student();s3.setId(3);s3.setName(网二);s3.setAge(30);list.add(s1);list.add(s2);list.add(s3);System.out.println(============================);int suma = list.stream().map(e -> e.getAge()).reduce(Integer::sum).get();///求和Systemememsssystememem.out.println(suma);int maxa = list.stream().map(e -> e.getAge()).reduce(Integer::max).get();////最大Systemem最大em最大.out.println(maxa);int mina = list.stream().map(e -> e.getAge()).reduce(Integer::min).get();////最小Systemem最小em最小.out.println(mina);System.out.println===============================;double doublesum = list.stream().mapToDouble(Student::getAge).sum();//和System.out.println(doublesum);int intmax = list.stream().mapToInt(Student::getAge).max().getAsInt();////最大Systemem最大em最大.out.println(intmax);int intmin = list.stream().mapToInt(Student::getAge).min().getAsInt();////最小Systemem最小em最小.out.println(intmin);double avg = list.stream().mapToDouble(Student::getAge).average().getAsDouble();///平均Systememem平均.out.println(avg);}}