如何对Collectors.Counting()的结果进行算术运算?

问题描述 投票:0回答:1

鉴于:

List<Integer> myIntegers = Arrays.asList(1, 1, 2, 3, 4, 2);

返回:

一个整数 = Sum(((整数的频率) / 2)))

我可以使用 Collectors.groupingBy() 获取每个整数的频率,但希望将每个频率值除以 2,然后对映射中的所有值求和,仅返回一个整数:

Map<Integer, Long> myIntegerMap = myIntegers.stream().collect(Collectors.groupingby(Function.identity(), Collectors.counting()));

for(Map.Entry<Integer, Long> a : myIntegerMap.entrySet()){ System.out.print(a.getKey(), + "==>"); System.out.println(a.getValue());}

输出:

1 ==> 2

2 ==> 2

3 ==> 1

4 ==> 1

所需输出:

( ( 2 / 2 ) + ( 2 / 2 ) + ( 1 / 2 ) + ( 1 / 2 ) ) = 2

java dictionary stream collectors
1个回答
0
投票

您可以使用映射缩减方法来做到这一点,如下所示:

  Long result = myIntegerMap.values().stream()
            .map(aLong -> aLong / 2)
            .reduce(0L, Long::sum);

希望我没有误解你的问题,这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.