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 get percentage of object in Java Streams

I have stream of integers and I try to find percentage of 1’s over all. I cannot find the solution.

connections
        .flatMap(co -> co.stops().stream())
        .map(ts -> ts.kind() == kind ? 1.0 : 0.0)

I don’t want to share class types and make things complicated. I just want to calculate percentage.

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

>Solution :

Rather than map, use mapToInt to get an IntStream, and then average() will get you the percentage you want:

.mapToInt(ts -> ts.kind() == kind ? 1 : 0).average()

This gives you an OptionalDouble, which will be empty if the stream is empty.

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