我有一个按出现次数分组的数字列表。例如,my list is { 1, 2, 1, 1, 2, 3 }分组列表将如下所示:
{
{ Key = 1, Value = { 1, 1, 1 } },
{ Key = 2, Value = { 2, 2 } },
{ Key = 3, Value = { 3 } }
}下面是这个分组的代码:
Map<Integer, List<Integer>> groups = input.stream().collect(Collerctors.groupingBy(x -> x));现在,对于这些组中的每一个,我想要获得配对。所以对于1,只有一对,最后一个1被省略了。对于2,我们也有一双,对于3,我们没有。所以我想得到每个组的大小,然后除以2。最后,我需要对所有这些结果进行求和。然而,我不知道如何在java中执行这样的投影。在C#中,我会这样做:
var result = groups.Select(x => x.ToList().Count / 2).Sum();我想在Java中我会使用collect-function,但我无法获得它:
Integer result = groups.stream().collect(...)发布于 2020-01-19 22:46:31
首先,您可以将一个counting Collector链接到groupingBy,这样Map的值就是每个组的元素数。
然后,您可以对这些值执行Stream操作,再除以2,然后计算和。
input.stream()
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
.values()
.stream()
.mapToLong(i -> i/2)
.sum();这将为示例输入返回2。
发布于 2020-01-19 22:58:46
我通过使用Collectors.summingInt让它正常工作
Integer result = groups.entrySet()
.stream()
.collect(Collectors.summingInt(x -> x.getValue().size() / 2)https://stackoverflow.com/questions/59811103
复制相似问题