How to convert following code using stream without using for each loop.
List<Topic>
. all List should be combined as List<Topic>
. Map<id,topicName>
from List<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));
}
Use flatMap
here, to not stream again. Just notice that this toMap
assumes that there will be no duplicate keys (or nulls)
list.stream()
.filter(e -> subjectId.equals(e.getId()))
.flatMap(subject -> subject.getTopics().stream())
.collect(Collectors.toMap(Topic::getId, Topic::getName));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With