【问题标题】:How to group and count elements in a sublist using java streams如何使用 java 流对子列表中的元素进行分组和计数
【发布时间】:2019-03-04 17:16:47
【问题描述】:

我想使用 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&lt;Long&gt; choiceIds 中。

class AnswerWithMultipleCorrectOptions {
     List<Long> choiceIds;
}

如何按List&lt;Long&gt; choiceIds 中的choiceId 分组并计数?

【问题讨论】:

  • 我不明白你想如何找到“多个”选项。您的意思是要检查ids 的整个列表而不是getId 以获得正确答案?它是如何工作的,你能用循环而不是流向我们展示吗?
  • 你能展示一些示例输入和输出吗?
  • 是的。如果用户只选择了一个选项,它将被保存在 answer.id 中。如果他选择了多个答案,我会将其添加到列表 answer.ids 中。我在问题中提到的代码适用于 answer.id。如果我有 answer.ids 而不是 answer.id,我该如何分组和计数?
  • id 是否可能在 ids 中重复?换句话说,id 总是与ids 中的所有答案不同,还是可能包含在ids 的列表中? (顺便说一句,这是一个糟糕的设计。最好只有一个答案列表,如果用户只选择一个,那么列表的长度为 1。)
  • 你期望什么样的地图?

标签: java java-stream grouping counting


【解决方案1】:

如果用户只选择了一个选项,它将被保存在 answer.id 中。如果他选择了多个答案,我会将其添加到列表 answer.ids 中。

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

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

但如果您想按List&lt;Long&gt; 分组,也可以使用相同的方式:

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

【讨论】:

  • 我可以使用 Answer::getIds() 获取 Map, Long>。有什么方法可以通过对子列表中的元素进行分组和计数来获得 Map
  • 做到了。谢谢@Rusian
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多