业务描述:
多名学生参加多门考试,有的科目没有参加故成绩为null
需要找出缺考学生都叫什么名字
public class Case_1 {
@Data
@AllArgsConstructor
static class StudentScore {
String studentName;
Integer scoreValue;//成绩
String subject;//科目
}
public static void main(String[] args) {
/*
业务描述:
多名学生参加多门考试,有的科目没有参加故成绩为null
需要找出缺考学生都叫什么名字
*/
Map<String, List<StudentScore>> studentMap = new HashMap<>();
List<StudentScore> zsScoreList = new ArrayList<>();
zsScoreList.add(new StudentScore("张三", 30, "CHINESE"));
zsScoreList.add(new StudentScore("张三", 40, "ENGLISH"));
zsScoreList.add(new StudentScore("张三",50,"MATHS"));
studentMap.put("张三", zsScoreList);
List<StudentScore> lsScoreList = new ArrayList<>();
lsScoreList.add(new StudentScore("李四",80,"CHINESE"));
lsScoreList.add(new StudentScore("李四",null,"ENGLISH"));
lsScoreList.add(new StudentScore("李四",100,"MATHS"));
studentMap.put("李四", lsScoreList);
List<StudentScore> wwScoreList = new ArrayList<>();
wwScoreList.add(new StudentScore("王五",null,"CHINESE"));
wwScoreList.add(new StudentScore("王五",null,"ENGLISH"));
wwScoreList.add(new StudentScore("王五",70,"MATHS"));
studentMap.put("王五", wwScoreList);
studentMap.forEach(
(studentName, scoreList) -> {
boolean result = scoreList.stream()
.anyMatch(score -> {
return score.getScoreValue() == null;
});
if (result) {
System.out.println("此学生【 " + studentName + " 】有缺考情况");
}
}
);
}
}
拓展练习:找出都是谁缺了哪门课的考试。
按理说应该有更简单更快捷的流式代码,我没有写出来,惭愧。
注:这里用的是allMatch,判断条件是(!=null),我在写的时候,用==null试了试,没有完全打印出结果,改成!=null后,会循环打印出结果。我还没搞清楚这里为啥。
studentMap.forEach((name, list) -> {
Map<String, List<StudentScore>> collect = list.stream().collect(Collectors.groupingBy(s -> s.getStudentName()));
for (Map.Entry<String, List<StudentScore>> entry : collect.entrySet()) {
String stuName = entry.getKey();
List<StudentScore> scoreList = entry.getValue();
for (StudentScore studentScore : scoreList) {
Integer value = studentScore.getScoreValue();
String s = studentScore.getSubject();
if (value == null) {
System.out.println("学生【" + stuName + "】有缺考现象" + ",课程是:" + s);
}
}
}
});