Home > Blockchain >  Stream API, is there way to iterate descending using instream.range?
Stream API, is there way to iterate descending using instream.range?

Time:01-09

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?

CodePudding user response:

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).limit(11)

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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
  •  Tags:  
  • Related