如何使用流转换以下代码而不使用每个循环。
List<Topic>
。所有列表应合并为List<Topic>
。 Map<id,topicName>
List<Topic>
醇>
对象模型:
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));
}
答案 0 :(得分:7)
在此处使用flatMap
,不再播放。请注意,此toMap
假定不会有重复的键(或空值)
list.stream()
.filter(e -> subjectId.equals(e.getId()))
.flatMap(subject -> subject.getTopics().stream())
.collect(Collectors.toMap(Topic::getId, Topic::getName));