How to convert following code using stream without using for each loop.
- getAllSubjects() returns all List and each Subject has
List<Topic>
. all List should be combined asList<Topic>
. - Needs to get
Map<id,topicName>
fromList<Topic>
Object Model:
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));
}