Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to perform arithmetic on the result of Collectors.Counting()?

Given:

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

Return:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading