import lombok.Data; import lombok.extern.slf4j.Slf4j; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * @Author weijun.nie * @Date 2020/5/25 17:37 * @Version 1.0 */ @Data @Slf4j public class Student { // 姓名 private String name; // 年齡 private int age; // 性別 private Gender gender; // 小區 private Community community; public Student(String name, int age, Gender gender, Community community) { this.name = name; this.age = age; this.gender = gender; this.community = community; } @Data static class Community { private String address; private String name; private int count; // 小區人數 public Community(String address, String name, int count) { this.address = address; this.name = name; this.count = count; } } public enum Gender { MALE, FEMALE; } public static void main(String[] args) { Community hdb = new Community("黃渠頭路", "海德堡", 2000); Community yglz = new Community("黃渠頭路", "陽光麗茲", 1500); Community tdzy = new Community("黃渠頭路", "唐頓莊園", 1000); Community qjld = new Community("雁翔路", "曲江龍邸", 1000); List<Student> students = Arrays.asList( new Student("小黑", 5, Gender.MALE, hdb), new Student("小白", 6, Gender.FEMALE, hdb), new Student("小紅", 7, Gender.FEMALE, yglz), new Student("小藍", 5, Gender.MALE, tdzy), new Student("小陳", 3, Gender.FEMALE, hdb), new Student("小張", 3, Gender.MALE, yglz), new Student("小吳", 5, Gender.MALE, hdb), new Student("小劉", 12, Gender.FEMALE, hdb), new Student("大牛", 16, Gender.MALE, qjld), new Student("大李", 15, Gender.MALE, hdb), new Student("大Q", 42, Gender.FEMALE, qjld), new Student("大E", 35, Gender.MALE, hdb) ); // 1. 彙總小區名爲"海德堡"的學生的總數; long count = students.stream().filter(s -> hdb == s.getCommunity()).count(); log.info("彙總小區名爲 海德堡 的學生的總數:{}", count); // 2. 彙總小區名爲"海德堡"的學生的姓名集合; List<String> hdbStudentNames = students.stream().filter(s -> s.getCommunity() == hdb).map(s -> s.getName()).collect(Collectors.toList()); log.info("彙總小區名爲 海德堡 的學生的姓名集合", hdbStudentNames); // 3. 返回住在陽光麗茲+海德堡的學生的平均年齡; Double collect = students.stream().filter(s -> s.getCommunity() == tdzy || s.getCommunity() == yglz).collect(Collectors.averagingInt(Student::getAge)); log.info("住在陽光麗茲+海德堡的學生的平均年齡爲:{}歲", collect); // 4. 拿到年齡大於平均年齡的全部學生的姓名集合; Double avgAge = students.stream().collect(Collectors.averagingInt(Student::getAge)); Set set = students.stream().filter(s -> s.getAge() > avgAge).map(Student::getName).collect(Collectors.toCollection(HashSet::new)); log.info("全部學平生均年齡:{}, 大於平均年齡的學生有:{}", avgAge, set); } }
彙總小區名爲 海德堡 的學生的總數:7 彙總小區名爲 海德堡 的學生的姓名集合 住在陽光麗茲+海德堡的學生的平均年齡爲:5.0歲 全部學平生均年齡:12.833333333333334, 大於平均年齡的學生有:[大Q, 大E, 大李, 大牛]