How to Use Java IntStream

IntStream supports creating sequences of primitive integer elements and parallel aggregate processing.

How to Use IntStream

IntStream supports creating sequences of primitive integer elements and parallel aggregate processing.

package com.devkuma.basic.stream;

import java.util.stream.IntStream;

public class IntStreamRange {

    public static void main(String[] args) {
        System.out.println("range:");
        IntStream.range(0, 10).forEach(System.out::println);

        System.out.println("rangeClosed:");
        IntStream.rangeClosed(0, 10).forEach(System.out::println);

        System.out.println("sum:");
        System.out.println(IntStream.range(0, 10).sum());

        System.out.println("max:");
        System.out.println(IntStream.range(0, 10).max());

        System.out.println("min:");
        System.out.println(IntStream.range(0, 10).min());

        System.out.println("average:");
        System.out.println(IntStream.range(0, 10).average());
    }
}

range()

The following example displays values from 0 to 9. range() does not include the end value.

IntStream.range(0, 10).forEach(System.out::println);

Result:

0
1
2
3
4
5
6
7
8
9

rangeClosed()

The following example displays values from 0 to 10. rangeClosed() includes the end value.

IntStream.rangeClosed(0, 10).forEach(System.out::println);

Result:

0
1
2
3
4
5
6
7
8
9
10

sum()

sum() can calculate the sum from 0 to 10 as follows.

System.out.println(IntStream.range(0, 10).sum());

Result:

45

max()

max() can easily find the maximum value.

System.out.println(IntStream.range(0, 10).max());

Result:

OptionalInt[9]

min()

min() can easily find the minimum value.

System.out.println(IntStream.range(0, 10).min());

Result:

OptionalInt[0]

average()

average() can calculate the average.

System.out.println(IntStream.range(0, 10).average());

Result:

OptionalDouble[4.5]
  • LongStream
  • DoubleStream