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?
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?
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) i-1 instead of --iYou 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.
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