6

For example, Instream.range(0,10) - is iterating from 0 index to 10.

Instream.range(10,0) - but from 10 to 0 is not working, how to do it using Stream API?

Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • 1
    Does this answer your question? [Java 8 stream reverse order](https://stackoverflow.com/questions/24010109/java-8-stream-reverse-order) – Apokralipsa Jan 08 '22 at 12:18
  • @Apokralipsa If possible, I would recommend to avoid sorting in this circumstance since sorting is a stateful operation. – Turing85 Jan 08 '22 at 12:21

5 Answers5

10

You can use IntStream.iterate(initialValue, hasNext, next):

IntStream.iterate(10, i -> i >= 0, i -> i - 1)

If you are stuck with java 8:

IntStream.iterate(10, i -> i - 1).limit(11)
JEY
  • 6,973
  • 1
  • 36
  • 51
3

You cannot generate descending stream using range(). Java doc clearly specifies that the steps are an increment of 1. If there was an option to provide a step then we could have. However, there are different ways in which you can achieve the same.

IntStream.iterate(10, i -> i >= 1, i -> --i)


IntStream.rangeClosed(1, 10).boxed().sorted(Comparator.reverseOrder())


IntStream.range(-10, 0).map(i -> -i)

Out of this three using and iterate method would be the best approach.

Tarun
  • 121
  • 7
  • "sorted" that's bad, because it holds all values in memory before you can use it – Yura Jan 13 '22 at 16:08
  • Yup I know it's bad, I was just listing out the possible ways. I have also added a note at the end. – Tarun Jan 14 '22 at 09:40
1

If you want the same set of numbers to be repeated if start/end are transposed then this will replace the ranges if start > end:

IntStream range(int start, int end) {
    return start < end ? IntStream.range(start,end) 
                       : IntStream.range(-start+1, -end+1).map(i -> -i);
}
range(2,5).forEach(System.out::println);
2
3
4

range(5,2).forEach(System.out::println)
4
3
2

If you want the meaning of (startInclusive, endExclusive) to be preserved modify as:

IntStream range2(int start, int end) {
    return start < end ? IntStream.range(start,end) 
                       : IntStream.range(-start, -end).map(i -> -i);
}

range2(5,2).forEach(System.out::println)
5
4
3
DuncG
  • 12,137
  • 2
  • 21
  • 33
0

Another trade-off solution is modify the range value like :

    int exclusiveEnd = 10;
    IntStream.range(0, exclusiveEnd).forEach((i) -> {
        System.out.println(exclusiveEnd - 1 - i);
    });
0

Use map after range to calculate new value:

IntStream.range(0, 10).map(i -> 10 - i); // 10, 9, .. 1
IntStream.rangeClosed(0, 10).map(i -> 10 - i); // 10, 9, .. 0
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42