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.
>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.