回答編集履歴

2

java.util.stream.Streamに訂正

2020/01/03 16:41

投稿

xebme
xebme

スコア1083

test CHANGED
@@ -32,7 +32,7 @@
32
32
 
33
33
 
34
34
 
35
- **java.util.Streamを使用する統計処理(追記)**
35
+ **java.util.stream.Streamを使用する統計処理(追記)**
36
36
 
37
37
 
38
38
 

1

java.util.Streamを使用する例を追記

2020/01/03 16:41

投稿

xebme
xebme

スコア1083

test CHANGED
@@ -28,4 +28,114 @@
28
28
 
29
29
  ```
30
30
 
31
- `""`の代わりに奪三振率の高い`"Yu Darvish"` としたいですね。
31
+ `""`の代わりに奪三振率の高い`"Yu Darvish"` としたいですね。(文字列リテラルなら何でもよい)
32
+
33
+
34
+
35
+ **java.util.Streamを使用する統計処理(追記)**
36
+
37
+
38
+
39
+ バッターの打率を集計する専用クラス。Streamを使用して作り直したソースを追記します。
40
+
41
+ ```Java
42
+
43
+ import java.io.BufferedReader;
44
+
45
+ import java.io.FileReader;
46
+
47
+ import java.io.IOException;
48
+
49
+ import java.io.PrintStream;
50
+
51
+ import java.util.Map;
52
+
53
+ import java.util.TreeMap;
54
+
55
+ import java.util.AbstractMap.SimpleEntry;
56
+
57
+ import java.util.stream.Collectors;
58
+
59
+ import java.util.stream.Stream;
60
+
61
+
62
+
63
+ public class EvaConv2 {
64
+
65
+
66
+
67
+ public static void main(String[] args) {
68
+
69
+ try {
70
+
71
+ PlayerMatrix.read("ファイル名.EVA").writeTo(System.out);
72
+
73
+ } catch (IOException e) {
74
+
75
+ e.printStackTrace();
76
+
77
+ }
78
+
79
+ }
80
+
81
+
82
+
83
+ private static class PlayerMatrix {
84
+
85
+ private final Map<String, Double> freqs;
86
+
87
+
88
+
89
+ public PlayerMatrix(Stream<String> lines) throws IOException {
90
+
91
+ freqs = lines.map(
92
+
93
+ line -> {String[] t = line.split(","); return new SimpleEntry<>(t[3], t[16]);
94
+
95
+ }).collect(
96
+
97
+ Collectors.groupingBy(
98
+
99
+ SimpleEntry::getKey,
100
+
101
+ TreeMap::new,
102
+
103
+ Collectors.averagingDouble(e -> Double.valueOf(e.getValue()))
104
+
105
+ ));
106
+
107
+ }
108
+
109
+
110
+
111
+ void writeTo(PrintStream out) {
112
+
113
+ out.println("player,batting average (BA)");
114
+
115
+ freqs.entrySet().forEach(e -> out.printf("%s,%1.3f\n", e.getKey(), e.getValue()));
116
+
117
+ }
118
+
119
+
120
+
121
+ static PlayerMatrix read(String filename) throws IOException {
122
+
123
+ PlayerMatrix matrix = null;
124
+
125
+ try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
126
+
127
+ matrix = new PlayerMatrix(br.lines());
128
+
129
+ }
130
+
131
+ return matrix;
132
+
133
+ }
134
+
135
+ }
136
+
137
+ }
138
+
139
+ ```
140
+
141
+ たぶんこれより`R`で作る方が簡単でしょう。