0
0

More than 3 years have passed since last update.

IntStream reduce()初期値有り時の挙動

Last updated at Posted at 2021-08-24

はじめに

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
0
0
11

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0