请按以下步骤实现代码
-
创建一个新的 JDK 1.8 项目,能运行 main 方法即可
-
新建一个 Record 类,类中包含以下属性 level, teacher, student
-
构建一个 List 集合,集合中包含 8 个 Record 对象, Record 对象包含以下属性:
Level(年级),Teacher(老师姓名),Student(学生姓名)每个对象的属性值如下:
Level | Teacher | Student |
---|---|---|
L1 | Li | S1 |
L1 | Wang | S2 |
L1 | Wang | S3 |
L2 | Li | S4 |
L2 | Li | S5 |
L2 | Wang | S6 |
L3 | Wang | S7 |
L3 | Wang | S8 |
然后实现以下数据统计,要求使用 Java 8 的 Stream 和 Lambda 表达式
-
使用 Stream 集合操作统计每个年级有多少名学生,打印在输出窗口即可,输出效果:
{L1=3, L2=3, L3=2} -
使用 filter 方法进行过滤,列出老师 Li 的所有学生姓名,输出效果:
{Li=[S1, S4, S5]} -
列出每个老师,每个年级的学生数量,输出效果:
{Wang={L1=2, L2=1, L3=2}, Li={L1=1, L2=2}}
可参考 Java 文档:https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
答案
新建一个 TestRecord
类,把以下代码赋值复制进入
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;public class TestRecord {public static void main(String[] args) {List<Record> list = new ArrayList<>();list.add(new Record("L1", "Li", "S1"));list.add(new Record("L1", "Wang", "S2"));list.add(new Record("L1", "Wang", "S3"));list.add(new Record("L2", "Li", "S4"));list.add(new Record("L2", "Li", "S5"));list.add(new Record("L2", "Wang", "S6"));list.add(new Record("L3", "Wang", "S7"));list.add(new Record("L3", "Wang", "S8"));// 使用 Stream 集合操作统计每个年级有多少名学生,打印在输出窗口即可,输出效果: {L1=3, L2=3, L3=2}Map<String, Long> record1 = list.stream().collect(Collectors.groupingBy(Record::getLevel, Collectors.counting()));System.out.println(record1);// 使用 filter 方法进行过滤,列出老师 Li 的所有学生姓名,输出效果: {Li=[S1, S4, S5]}Map<String, List<String>> result = list.stream().filter(record -> "Li".equals(record.getTeacher())).collect(Collectors.groupingBy(Record::getTeacher, Collectors.mapping(Record::getStudent, Collectors.toList())));System.out.println(result);// 列出每个老师,每个年级的学生数量Map<String,Map<String,Long>> collect = list.stream().collect(Collectors.groupingBy(Record::getTeacher,Collectors.groupingBy(Record::getLevel,Collectors.counting())));System.out.println(collect);}
}class Record {private String level;private String teacher;private String student;public Record() {}public Record(String level, String teacher, String student) {this.level = level;this.teacher = teacher;this.student = student;}public String getLevel() {return level;}public void setLevel(String level) {this.level = level;}public String getTeacher() {return teacher;}public void setTeacher(String teacher) {this.teacher = teacher;}public String getStudent() {return student;}public void setStudent(String student) {this.student = student;}@Overridepublic String toString() {return "Record{" +"level='" + level + '\'' +", teacher='" + teacher + '\'' +", student='" + student + '\'' +'}';}
}
结果
{L1=3, L2=3, L3=2}
{Li=[S1, S4, S5]}
{Wang={L1=2, L2=1, L3=2}, Li={L1=1, L2=2}}