如何使用Stream将以下代码转换而不使用 for each 循环。
getAllSubjects()
返回所有列表,每个主题都有一个List<Topic>
。所有列表应合并为List<Topic>
。- 需要从
List<Topic>
中获取Map<id,topicName>
。
对象模型:
Subject
id,....
List<Topic>
Topic
id,name
public Map<String, String> getSubjectIdAndName(final String subjectId) {
List<Subject> list = getAllSubjects(); // api method returns all subjects
//NEEDS TO IMPROVE CODE USING STREAMS
list = list.stream().filter(e -> e.getId().equals(subjectId)).collect(Collectors.toList());
List<Topic> topicList = new ArrayList<>();
for (Subject s : list) {
List<Topic> tlist = s.getTopics();
topicList.addAll(tlist);
}
return topicList.stream().collect(Collectors.toMap(Topic::getId, Topic::getName));
}
List
,然后学习flatMap
,就可以完成了。换句话说,return getAllSubjects() .stream() .filter(e -> e.getId().equals(subjectId)) .flatMap(s -> s.getTopics().stream()) .collect(Collectors.toMap(Topic::getId, Topic::getName));
。 - Holger