-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample179.java
More file actions
70 lines (60 loc) · 2.46 KB
/
Example179.java
File metadata and controls
70 lines (60 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Example 179 from page 141
//
import java.util.DoubleSummaryStatistics;
import java.util.stream.DoubleStream;
class Example179 {
public static void main(String[] args) {
simpleStatistics();
betterStatistics();
// uselesslyConsumedTwice();
}
private static void simpleStatistics() {
DoubleStream ds = DoubleStream.of(2, 4, 4, 4, 5, 5, 7, 9);
DoubleSummaryStatistics stats = ds.summaryStatistics();
// DoubleSummaryStatistics stats
// = ds.collect(DoubleSummaryStatistics::new,
// DoubleSummaryStatistics::accept,
// DoubleSummaryStatistics::combine);
System.out.printf("count=%d, min=%g, max=%g, sum=%g, mean=%g%n",
stats.getCount(), stats.getMin(), stats.getMax(),
stats.getSum(), stats.getAverage());
}
// How to extend DoubleSummaryStatistics to also compute standard
// deviation. Since a stream cannot be consumed twice, we do it in
// one pass by subclassing instead of, say, computing the mean in a
// first pass and then computing the standard deviation in the
// second pass, although that would be numerically better.
private static void betterStatistics() {
DoubleStream ds = DoubleStream.of(2, 4, 4, 4, 5, 5, 7, 9);
BetterDoubleStatistics stats
= ds.collect(BetterDoubleStatistics::new,
BetterDoubleStatistics::accept,
BetterDoubleStatistics::combine);
System.out.printf("count=%d, min=%g, max=%g, sum=%g, mean=%g, sdev=%g%n",
stats.getCount(), stats.getMin(), stats.getMax(),
stats.getSum(), stats.getAverage(), stats.getSdev());
}
private static void uselesslyConsumedTwice() {
DoubleStream ds = DoubleStream.of(2, 4, 4, 4, 5, 5, 7, 9);
DoubleSummaryStatistics stats = ds.summaryStatistics();
// This throws IllegalStateException: stream has already been operated upon or closed:
double sqsum = ds.map(x -> x*x).sum();
double sdev = Math.sqrt(sqsum/stats.getCount() - stats.getAverage()*stats.getAverage());
}
}
class BetterDoubleStatistics extends DoubleSummaryStatistics {
private double sqsum = 0.0;
@Override
public void accept(double d) {
super.accept(d);
sqsum += d * d;
}
public void combine(BetterDoubleStatistics other) {
super.combine(other);
sqsum += other.sqsum;
}
public double getSdev() {
double mean = getAverage();
return Math.sqrt(sqsum/getCount() - mean*mean);
}
}