这个问题在这里已有答案:
如何使用流转换以下代码而不使用每个循环。
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));
}
在这里使用flatMap
,不再流。请注意,这个toMap
假设没有重复的键(或空值)
list.stream()
.filter(e -> subjectId.equals(e.getId()))
.flatMap(subject -> subject.getTopics().stream())
.collect(Collectors.toMap(Topic::getId, Topic::getName));