[Java]Stream#reduce() 要素数が0個/1個の時の挙動は?
リファレンスに内部実装の参考が載っていました。
Optional reduce(BinaryOperator accumulator)
これは、次の操作に相当します。
これは、次の操作に相当します。
boolean foundAny = false; T result = null; for (T element : this stream) { if (!foundAny) { foundAny = true; result = element; } else result = accumulator.apply(result, element); } return foundAny ? Optional.of(result) : Optional.empty();
要素数 | 結果 |
---|---|
0 | Optional.empty() |
1 | Optional.of(要素そのまま) |
2以上 | Optional.of(演算結果) |
Optional.empty()
が返ってくる可能性があるため、orElse()
にて判定をする必要があります。
要素数が0の可能性があるときは、以下の単位元(初期値)付きのメソッドを使用することで、それを回避できます。
T reduce(T identity, BinaryOperator accumulator)
identity値はアキュムレータ関数の単位元でなければいけません。
つまり、すべてのtについて、accumulator.apply(identity, t)がtに等しくなります。
identity値はアキュムレータ関数の単位元でなければいけません。
つまり、すべてのtについて、accumulator.apply(identity, t)がtに等しくなります。
T result = identity; for (T element : this stream) result = accumulator.apply(result, element) return result;
要素数 | 結果 |
---|---|
0 | 単位元(identity) |
1 | 要素そのまま |
2以上 | 演算結果 |