鉴于:
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
您可以使用映射缩减方法来做到这一点,如下所示:
Long result = myIntegerMap.values().stream()
.map(aLong -> aLong / 2)
.reduce(0L, Long::sum);
希望我没有误解你的问题,这会有所帮助。