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?

2
  • 1
    Does this answer your question? Java 8 stream reverse order Commented Jan 8, 2022 at 12:18
  • @Apokralipsa If possible, I would recommend to avoid sorting in this circumstance since sorting is a stateful operation. Commented Jan 8, 2022 at 12:21

5 Answers 5

11

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

I recommend i-1 instead of --i
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.

2 Comments

"sorted" that's bad, because it holds all values in memory before you can use it
Yup I know it's bad, I was just listing out the possible ways. I have also added a note at the end.
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 

Comments

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); }); 

Comments

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 

Comments