はじめに
IntStreamのreduce()の初期値(第一引数)の有無で
ループの回数が変わるということに
気が付きましたので書き残します。
初期値が無いとループの回数が1回減ります。
ので注意が必要です。
初期値無しの場合
reduce((total,i)-> total + i)
0回目無し
1回目から
Test.java
int result = IntStream.range(0, 4)
.reduce((total, i) -> {
System.out.println(i + "回目");
return total + i;
})
.orElseThrow();
System.out.println("result:" + result);
実行結果
1回目
2回目
3回目
result:6
初期値(0)有りの場合
reduce(0, (total,i)-> total + i)
0回目から
Test.java
public static void main(String[] args) {
int result = IntStream.range(0, 4)
.reduce(0, (total, i) -> {
System.out.println(i + "回目");
return total + i;
});
System.out.println("result:" + result);
実行結果
0回目
1回目
2回目
3回目
result:6
初期値(2)有りの場合
reduce(2, (total,i)-> total + i)
0回目から
Test.java
public static void main(String[] args) {
int result = IntStream.range(0, array.length)
.reduce(2, (total, i) -> {
System.out.println(i + "回目");
return total + i;
});
System.out.println("result:" + result);
実行結果
0回目
1回目
2回目
3回目
result:8