Home > Software design >  How to get percentage of object in Java Streams
How to get percentage of object in Java Streams

Time:12-24

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.

CodePudding user response:

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.

CodePudding user response:

You could use the summary statistics of a DoubleStream:

DoubleSummaryStatistics stats = connections.flatMap(co -> co.stops().stream())
        .mapToDouble(ts -> ts.kind() == kind ? 1.0 : 0.0)
        .summaryStatistics();
double percentage = 100 * stats.getSum() / stats.getCount();
// or
double percentage2 = 100 * stats.getAverage()
  • Related