2

I want used `IntStream' for executing back range.

So, ordinary IntStream.range look like:

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

But I need, like this:

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

How to realize it?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Valentyn Hruzytskyi
  • 1,772
  • 5
  • 27
  • 59

2 Answers2

3

Check these examples

import java.util.stream.IntStream;

// Generate an IntStream in Decreasing Order in Java
class StreamUtils
{
    public static void main(String[] args)
    {
        int start = 2;  // inclusive
        int end = 5;    // exclusive

        IntStream.iterate(end - 1, i -> i - 1)
                .limit(end - start)
                .forEach(System.out::println);
    }
}
boden
  • 1,621
  • 1
  • 21
  • 42
2

One way is to calculate the reverse number:

IntStream.range(1, 10)
         .map(i -> 10 - i)
         .forEach(System.out::println);

Output

9
8
7
6
5
4
3
2
1

Remember, range is upper-exclusive, so range(1, 10) generates the numbers 1-9. I'm assuming here that your range(10, 1) should return the same numbers, but in descending order, so still "upper"-exclusive, which now means excluding the first value, not the last value.

Andreas
  • 154,647
  • 11
  • 152
  • 247