【问题标题】:how to get max values in array list java spring如何在数组列表java spring中获取最大值
【发布时间】:2021-12-18 10:20:16
【问题描述】:

我有要求:

"questionType": "questionType",
    "question": [
        {
            "questionId": "questionIdFirst",
            "answer": [
                {
                    "input": "input1",
                    "answerOption": [
                        {
                            "answerId": "AnswerId1",
                            "score": 7
                        }
                    ]
                },
                {
                    "input": "input2",
                    "answerOption": [
                        {
                            "answerId": "AnswerId2",
                            "score": 8
                        }
                    ]
                }
            ]
        },
        {
            "questionId": "questionIdSecond",
            "answer": [
                {
                    "input": "input3",
                    "answerOption": [
                        {
                            "answerId": "answerId",
                            "score": 9
                        }
                    ]
                },
                {
                    "input": "input4",
                    "answerOption": [
                        {
                            "answerId": "answerId",
                            "score": 10
                        }
                    ]
                }
            ]
        }
    ]
}

我想通过流过滤器或 foreach 在对象 answerOption 中获得 maxValues 分数,我该怎么做?

我尝试这样做但无法解决:

input.getQuestionnaire().getQuestion().stream()
                    .forEach(quest -> quest.getAnswer().stream()
                            .forEach(answer -> answer.getAnswerOption()
                                    .stream().max(Comparator.comparing(AnswerOption::getScore))));

然后,在我想获取 maxValues 时,我选择 DB,然后我想将 answerOption 替换为请求样本到数据库

【问题讨论】:

    标签: java arrays spring multidimensional-array foreach


    【解决方案1】:

    要在Questionnaire 中检索最高分数AnswerOption,请尝试以下操作(您需要flatMap 来展平内部列表并获得最大比较器结果作为输出)

    final Optional<AnswerOption> max = input.getQuestionnaire().getQuestion().stream().map(Question::getAnswer)
            .flatMap(Collection::stream)
            .map(Answer::getAnswerOption).flatMap(Collection::stream)
            .max(Comparator.comparing(AnswerOption::getScore));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-13
      • 1970-01-01
      • 2020-11-28
      • 1970-01-01
      相关资源
      最近更新 更多