の平均ます:JAVAJavaの8:複数の属性以下のクラスで
Long fooSum, barSum;
for(HelloWorld hw: helloWorldList){
fooSum += hw.getFoo();
barSum += hw.getBar();
}
Long fooAvg = fooSum/helloWorldList.size();
Long barAvg = barSum/helloWorldList.size();
: 私はList<HelloWorld> helloWorldList
@Data
public class HelloWorld {
private Long foo;
private Long bar;
}
OPTION 1にfooとbarの平均値を取得したいですオプション2:JAVA8
Double fooAvg = helloWorldList.stream().mapToLong(HelloWorld::foo).average().orElse(null);
Double barAvg = helloWorldList.stream().mapToLong(HelloWorld::bar).average().orElse(null);
どのアプローチが良いですか? これらの値を取得する方法はありますか?
回答編集:この質問は、重複としてマークされているが、bradimusからのコメントを読んだ後、私はこれを実装することになった:
import java.util.function.Consumer;
public class HelloWorldSummaryStatistics implements Consumer<HelloWorld> {
@Getter
private int fooTotal = 0;
@Getter
private int barTotal = 0;
@Getter
private int count = 0;
public HelloWorldSummaryStatistics() {
}
@Override
public void accept(HelloWorld helloWorld) {
fooTotal += helloWorld.getFoo();
barTotal += helloWorld.getBar();
count++;
}
public void combine(HelloWorldSummaryStatistics other) {
fooTotal += other.fooTotal;
barTotal += other.barTotal;
count += other.count;
}
public final double getFooAverage() {
return getCount() > 0 ? (double) getFooTotal()/getCount() : 0.0d;
}
public final double getBarAverage() {
return getCount() > 0 ? (double) getBarTotal()/getCount() : 0.0d;
}
@Override
public String toString() {
return String.format(
"%s{count=%d, fooAverage=%f, barAverage=%f}",
this.getClass().getSimpleName(),
getCount(),
getFooAverage(),
getBarAverage());
}
}
メインクラス:
HelloWorld a = new HelloWorld(5L, 1L);
HelloWorld b = new HelloWorld(5L, 2L);
HelloWorld c = new HelloWorld(5L, 4L);
List<HelloWorld> hwList = Arrays.asList(a, b, c);
HelloWorldSummaryStatistics helloWorldSummaryStatistics = hwList.stream()
.collect(HelloWorldSummaryStatistics::new, HelloWorldSummaryStatistics::accept, HelloWorldSummaryStatistics::combine);
System.out.println(helloWorldSummaryStatistics);
注:示唆したように高精度が必要な場合は他にBigIntegerなどを使用できます。
注:不要なオブジェクトの割り当てを避けるために、代わりに 'Long'の' long'を使用した場合最初のものは非常に良いだろう。また、整数除算に注意してください。 –
最初の方が良いのは、リストを1回だけインターラストするからです。 – f1sh
'Stream'を使用する場合は、独自の[reduce](https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html)を記述してください([' Averager'] (https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html#collect)例) – bradimus