IntStream from range

Description

We can use the following two methods from IntStream interfaces to create IntStream from a range of int values.


IntStream range(int start, int end)
IntStream rangeClosed(int start, int end).

They create an IntStream that contains ordered integers between the start and end.

The specified end is exclusive in the range() method and inclusive in the rangeClosed() method.

Example

The following code uses both methods to create an IntStream having integers 1, 2, 3, 4, and 5 as their elements:


import java.util.stream.IntStream;
//from ww  w  . j av  a 2 s . c om
public class Main {
  public static void main(String[] args) {
    IntStream oneToFive  = IntStream.range(1, 6);
    //IntStream oneToFive  = IntStream.rangeClosed(1, 5);
    oneToFive.forEach(System.out::println);
  }
}

Like the IntStream interface, the LongStream class also contains range() and rangeClosed() methods that takes arguments of type long and return a LongStream.

The code above generates the following result.





















Home »
  Java Streams »
    Tutorial »




Java Streams Tutorial