gpt4 book ai didi

java - 如何使用 java 流对子列表中的元素进行分组和计数

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:45:18 25 4
gpt4 key购买 nike

我想使用 java 流对子列表中的元素进行分组和计数。

例如,我有一个 AnswerWithOneCorrectOption 类型的答案,如下所示:

class AnswerWithOneCorrectOption {
Long choiceId;
}

该答案类型只有一个正确选项,存储在“AnswerWithOneCorrectOption.id”中。我正在通过 AnswerWithOneCorrectOption 的列表进行流式传输,基于 id 进行分组并使用以下方法进行计数:

private Map<Long, Long> countChoicesAndGroup(List<AnswerWithOneCorrectOption> answers){

Map<Long, Long> map = answers.parallelStream()
.collect(Collectors.groupingBy(AnswerWithOneCorrectOption::getChoiceId,
Collectors.counting()));

return map;
}

假设我有另一种可以有多个正确选项的答案类型。我将这些选项保存在 List<Long> choiceIds 中.

class AnswerWithMultipleCorrectOptions {
List<Long> choiceIds;
}

如何在 List<Long> choiceIds 中按 choiceId 进行分组数数?

最佳答案

If user chose only one option, it will be saved in answer.id. If he chooses more than one answer, I will add it to the list answer.ids.

最好使用AnswerList<Long> ids仅有的。如果用户只选择了一个选项,您将只有一个元素的列表。它允许您按答案分组(不要忘记 equals/hashcode)这两种情况:

Map<Answer, Long> collect = answers.stream()
.collect(groupingBy(Function.identity(), counting()));

但是如果你想按List<Long>分组可以用同样的方式完成:

Map<List<Long>, Long> collect = answers.stream()
.collect(groupingBy(Answer::choiceIds, counting()));

更新:要按子列表中的元素分组,您可以使用 flatMap之前:

Map<Long, Long> map = answers.stream()
.flatMap(answer -> answer.getIds().stream())
.collect(groupingBy(Function.identity(), counting()));

关于java - 如何使用 java 流对子列表中的元素进行分组和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54988327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com