Generate an IntStream in Decreasing Order in Java

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

 

1. IntStream.range() + map()

We know that IntStream.range() can be used to generate 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. IntStream.range() + Sorting

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

 

Download   Run Code

Output:

4
3
2

 

3. IntStream.iterate() + limit()

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

 

Download   Run Code

Output:

4
3
2

 

4. IntStream.generate() with AtomicInteger

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

 

Download   Run Code

Output:

4
3
2

 

5. IntStream.generate() with PrimitiveIterator.OfInt

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

 

Download   Run Code

Output:

4
3
2

 

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Leave a Reply

avatar
  Subscribe  
Notify of