This post will discuss how to generate an IntStream in decreasing order. In other words, generate integers in a specified range from high to low using streams in Java.

1. Using IntStream.range() with map() method

We know that IntStream.range() can generate a sequence of increasing values within the specified range. The idea is to map each value in such a manner that the resulting sequence is decreasing, as shown below:

Download  Run Code

Output:

4
3
2

2. Using IntStream.range() + Sorting

Here’s another approach that simply sorts the increasing sequence in reverse order to get the sequence in decreasing order.

Download  Run Code

Output:

4
3
2

3. Using IntStream.iterate() with limit() method

We can also use IntStream.iterate() method to get sequence in decreasing order. It takes two parameters – a starting value and a lambda expression that reduces the previous value by 1.

Download  Run Code

Output:

4
3
2

4. Using IntStream.generate() with AtomicInteger

We can also use IntStream.generate() with AtomicInteger to get an integer counter that is also thread-safe and call the decrementAndGet() method to get the sequence in decreasing order, as shown below:

Download  Run Code

Output:

4
3
2

5. Using IntStream.generate() with PrimitiveIterator.OfInt() method

We can also use PrimitiveIterator.OfInt with IntStream.generate(), as shown below:

Download  Run Code

Output:

4
3
2

That’s all about generating an IntStream in decreasing order in Java.