Given:
List<Integer> myIntegers = Arrays.asList(1, 1, 2, 3, 4, 2);
Return:
an Integer = Sum(((Frequency of Integer) / 2)))
I’m able to get the frequency of each integer using Collectors.groupingBy(), but want to then divide each frequency value by 2 and then sum all the values in the map, returning just an Integer:
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());}
Output:
1 ==> 2
2 ==> 2
3 ==> 1
4 ==> 1
Desired Output:
( ( 2 / 2 ) + ( 2 / 2 ) + ( 1 / 2 ) + ( 1 / 2 ) ) = 2
>Solution :
You can do that with a map-reduce approach like so:
long result = myIntegerMap.values().stream()
.mapToLong(aLong -> aLong / 2)
.sum();
Hope I didn’t misunderstand your question and this helps.