【问题标题】:Java 8 convert the list and sublist into a single mapJava 8 将列表和子列表转换为单个映射
【发布时间】:2019-11-19 04:51:17
【问题描述】:

我们如何在 java 8 中将列表和子列表转换为单个映射?

示例代码

Map<String, String> pepAnswersMap = new HashMap<>();
for (Iterator<PepQuestionsDTO> iterator = pepQuestions.iterator(); iterator.hasNext();) {
    PepQuestionsDTO pepQuestion = iterator.next();
    pepAnswersMap.put(pepQuestion.getSign(), pepQuestion.getAnswer().getAnswer());
    for (Iterator<SubQuestionsDTO> iterator2 = pepQuestion.getSubQuestions().iterator(); iterator2.hasNext();) {
        SubQuestionsDTO subQuestion = iterator2.next();
        pepAnswersMap.put(subQuestion.getSign(), subQuestion.getAnswer().getAnswer());
    }
}

【问题讨论】:

  • 你需要在你的问题中解释你想做什么。该代码没有解释任何内容,我们想知道您希望您的代码做什么,而它还没有做什么。
  • 我想把这个循环部分转换成 java8 流
  • 然后在你的问题中写下!当您使用它时,请编辑代码,使其成为一个最小的工作示例。 stackoverflow.com/help/minimal-reproducible-example

标签: java list java-8


【解决方案1】:

你可以这样做:

pepQuestionsDTOS.stream()
            .flatMap(pepQuestion -> {
                pepAnswersMap.put(pepQuestion.getSing(), pepQuestion.getAnswer().getAnswer());
                return pepQuestionsDTO.getSubQuestions().stream();
            })
            .map(subQuestion -> new AbstractMap.SimpleEntry<>(subQuestion.getSing(),
                                                     subQuestion.getAnswer().getAnswer()))
            .forEach(entry -> pepAnswersMap.put(entry.getKey(), entry.getValue()));

但我认为使用 forEach 循环更具可读性

 pepQuestionsDTOS.forEach(pepQuestion->
    {
        pepAnswersMap.put(pepQuestion.question, pepQuestion.getAnswer());
        pepQuestion.getSubQuestions()
                .forEach(pepQuestion ->
                 pepAnswersMap.put(pepQuestion.getSing(), pepQuestion.getAnswer().getAnswer()));
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多