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

284
Views
Stream API, ¿hay alguna forma de iterar descendente usando instream.range?

Por ejemplo, Instream.range(0,10) - está iterando desde el índice 0 hasta el 10.

Instream.range(10,0) - pero de 10 a 0 no funciona, ¿cómo hacerlo usando Stream API?

over 4 years ago · Santiago Trujillo
5 answers
Answer question

0

Puede usar IntStream.iterate (initialValue, hasNext, next):

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

Si estás atascado con Java 8:

 IntStream.iterate(10, i -> i - 1).limit(11)
over 4 years ago · Santiago Trujillo Report

0

No puede generar una secuencia descendente usando range(). Java doc especifica claramente que los pasos son un incremento de 1. Si hubiera una opción para proporcionar un paso, entonces podríamos tenerla. Sin embargo, hay diferentes maneras en las que puedes lograr lo mismo.

 IntStream.iterate(10, i -> i >= 1, i -> --i) IntStream.rangeClosed(1, 10).boxed().sorted(Comparator.reverseOrder()) IntStream.range(-10, 0).map(i -> -i)

De estos tres métodos de iteración y uso sería el mejor enfoque.

over 4 years ago · Santiago Trujillo Report

0

Otra solución de compensación es modificar el valor del rango como:

 int exclusiveEnd = 10; IntStream.range(0, exclusiveEnd).forEach((i) -> { System.out.println(exclusiveEnd - 1 - i); });
over 4 years ago · Santiago Trujillo Report

0

Use el map después del range para calcular el nuevo valor:

 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

Si desea que se repita el mismo conjunto de números si se transponen inicio/final, esto reemplazará los rangos si 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

Si desea que se conserve el significado de (startInclusive, endExclusive), modifíquelo como:

 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!