Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

287
Views
Stream API, is there way to iterate descending using instream.range?

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?

over 4 years ago · Santiago Trujillo
5 answers
Answer question

0

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)
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

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);
    });
over 4 years ago · Santiago Trujillo Report

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
over 4 years ago · Santiago Trujillo Report

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!