java8-10.1-IntSummaryStatistics 类的使用
public class Student { /** 学号 */ private long id; private String name; private int age; /** 年级 */ private int grade; /** 专业 */ private String major; /** 学校 */ private String school; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public Student(long id, String name, int age, int grade, String major, String school) { super(); this.id = id; this.name = name; this.age = age; this.grade = grade; this.major = major; this.school = school; } }
public class Test { public static void main(String[] args) { List<Student> students = Arrays.asList( new Student(200123,"苏明",20,1,"土木工程","苏州大学"), new Student(200456,"张阿凡",21,2,"机械工程","杭州师范大学"), new Student(200789,"范总",20,3,"计算机工程","苏州工业大学"), new Student(201123,"刘飞",22,1,"考古","上海大学"), new Student(202123,"万三",17,3,"历史","复旦大学"), new Student(203123,"克里",25,2,"数学","上海外国语大学") ); //第一种 集合有6条数据 System.out.println(students.size()); //第二种 集合有6条数据 long count = students.stream().count(); System.out.println(count); //第三种 集合有6条数据 Long count2 = students.stream().collect(Collectors.counting()); System.out.println(count2);
//第一种 年龄总和 Integer sumAge = students.stream().collect(Collectors.summingInt(Student::getAge)); System.out.println(sumAge); //第二种 年龄总和 long sum = students.stream().collect(Collectors.summarizingInt(Student::getAge)).getSum(); System.out.println(sum); //IntSummaryStatistics 一次性得到元素个数、总和、均值、最大值、最小值 IntSummaryStatistics summaryStatistics = students.stream() .collect(Collectors.summarizingInt(Student::getAge)); System.out.println(summaryStatistics.getCount()); System.out.println(summaryStatistics.getSum()); System.out.println(summaryStatistics.getAverage()); System.out.println(summaryStatistics.getMax()); System.out.println(summaryStatistics.getMin()); //纯数字的计算 List<Integer> integers = Arrays.asList(1,2,3,4,5,6,7,8,9,25); IntSummaryStatistics summary = integers.stream().mapToInt(T -> T).summaryStatistics(); System.out.println(summary.getAverage()); System.out.println(summary.getCount()); System.out.println(summary.getMax()); System.out.println(summary.getMin()); System.out.println(summary.getSum()); } }
古人学问无遗力,少壮工夫老始成。
纸上得来终觉浅,绝知此事要躬行。