How to convert List of Lists to single List using Java8 streams

Lakshman Miani :

How to convert following code using stream without using for each loop.

  1. getAllSubjects() returns all List and each Subject has List<Topic>. all List should be combined as List<Topic>.
  2. Needs to get 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));

}
Eugene :

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));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=475585&siteId=1