Difference between range() and rangeClosed() in Java Streams

In Java’s Stream API, the methods IntStream.range() and IntStream.rangeClosed() are used to generate streams of numbers. They differ in whether the upper bound of the range is included or not.

Here’s a breakdown of the differences:

1. IntStream.range(int startInclusive, int endExclusive)

  • Description:
    Generates a stream of integers starting from startInclusive (inclusive) and ending at endExclusive (exclusive). The upper bound is not included in the result.
  • Parameters:
  • startInclusive: The starting number of the range (included).
  • endExclusive: The ending number of the range (excluded).
  • Example:
  IntStream.range(1, 5).forEach(System.out::println);

Output:

  1
  2
  3
  4

In this case, the numbers 1, 2, 3, and 4 are included, but 5 is not included.


2. IntStream.rangeClosed(int startInclusive, int endInclusive)

  • Description:
    Generates a stream of integers starting from startInclusive (inclusive) and ending at endInclusive (inclusive). The upper bound is included in the result.
  • Parameters:
  • startInclusive: The starting number of the range (included).
  • endInclusive: The ending number of the range (included).
  • Example:
  IntStream.rangeClosed(1, 5).forEach(System.out::println);

Output:

  1
  2
  3
  4
  5

Here, the numbers 1, 2, 3, 4, and 5 are all included.


Key Differences:

  • Range:
  • IntStream.range(1, 5) → Generates numbers from 1 to 4 (upper bound excluded).
  • RangeClosed:
  • IntStream.rangeClosed(1, 5) → Generates numbers from 1 to 5 (upper bound included).

Summary:

  • range(): Generates a stream where the end is exclusive.
  • rangeClosed(): Generates a stream where the end is inclusive.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *