如何使用Java8流将列表列表转换为单个列表

时间:2018-02-28 10:16:05

标签: java java-8 java-stream

如何使用流转换以下代码而不使用每个循环。

  1. getAllSubjects()返回所有List,每个Subject都有List<Topic>。所有列表应合并为List<Topic>
  2. 需要Map<id,topicName>
  3. 获取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));
    
    }
    

1 个答案:

答案 0 :(得分:7)

在此处使用flatMap,不再播放。请注意,此toMap假定不会有重复的键(或空值)

list.stream()
    .filter(e -> subjectId.equals(e.getId()))
    .flatMap(subject -> subject.getTopics().stream())
    .collect(Collectors.toMap(Topic::getId, Topic::getName));