1.业务场景
一种选择题试卷(TestPaper)由N个试卷项(TestPaperItem)组成,一种试卷由N个学生作答,会产生N份答卷(answer),一份答卷由N个答卷项(answerItem)组成,一个答卷项由TestPaperItem的一个问题项、一个选项组成。
实体关系如下:
相应的表关系和实体关系一直,就不赘述。
需求:
相应的表关系和实体关系一直,就不赘述。
需求:
查出所有考试的答卷列表。
2.循环写法
原生写法,先获取testPaper列表,再通过testPaperId获取answer列表,再通过answerId获取answerItem列表。
整个代码就是多层嵌套循环,去拼最后的结果:
@RestController public class TestController { @Autowired TestPaperService testPaperService; @Autowired TestPaperItemService testPaperItemService; @Autowired AnswerService answerService; @Autowired AnswerItemService answerItemService; @GetMapping("getTestPaperList") public List<TestPaper> getTestPaperList(){ //获取试卷列表 List<TestPaper> testPaperList = testPaperService.getList(); for (TestPaper testPaper : testPaperList) { Answer answerQueryParam = new Answer(); answerQueryParam.setPaperId(testPaper.getId()); List<Answer> answerList = answerService.getList(answerQueryParam); testPaper.setAnswerList(answerList); for (Answer answer : answerList) { AnswerItem answerItemQueryParam = new AnswerItem(); List<AnswerItem> answerItemList = answerItemService.getList(answerItemQueryParam); answer.setAnswerItems(answerItemList); } } return testPaperList; } }
可以看到循环写法,代码过于冗长,看起来很吃力,改起来也很吃力。
3.stream写法
接下来我们看改成stream后整个流程会多么简洁、易读:
@RestController public class TestController { @Autowired TestPaperService testPaperService; @Autowired TestPaperItemService testPaperItemService; @Autowired AnswerService answerService; @Autowired AnswerItemService answerItemService; @GetMapping("getTestPaperList") public List<TestPaper> getTestPaperList() { return testPaperService.getList().stream() .peek(this::setAnswerList) .collect(Collectors.toList()); } private void setAnswerList(TestPaper testPaper) { Answer answerQueryParam = new Answer(); answerQueryParam.setPaperId(testPaper.getId()); List<Answer> answerList = answerService.getList(answerQueryParam); testPaper.setAnswerList(answerList); answerList.forEach(this::setAnswerItems); } private void setAnswerItems(Answer answer) { AnswerItem answerItemQueryParam = new AnswerItem(); List<AnswerItem> answerItemList = answerItemService.getList(answerItemQueryParam); answer.setAnswerItems(answerItemList); } }
4.总结
通过上面的示例,我们可以看到,java stream在业务流程中,很适合当一条组装逻辑的“主线”,将冗长的代码逻辑单独剔出来封装成方法,在主线上拼接逻辑,使得代码具有优秀的可读性。这是stream在实际生产中非常重要的价值。
关于stream的更多、更详细的知识可以移步作者另一篇文章: