The IntStream(since 1.8) class provides a range() method to produce a stream that is a sequence of int s.
case 1:
// streams/Ranges.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import static java.util.stream.IntStream.*;
public class Ranges {
public static void main(String[] args) {
// The traditional way:
int result = 0;
for (int i = 10; i < 20; i++) {
result += i;
}
System.out.println(result);
// for-in with a range:
result = 0;
for (int i : range(10, 20).toArray()) {
result += i;
}
System.out.println(result);
// Use streams:
System.out.println(range(10, 20).sum());
}
}
/* Output:
145
145
145
*/
case 2:
// onjava/Repeat.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package onjava;
import static java.util.stream.IntStream.*;
public class Repeat {
public static void repeat(int n, Runnable action) {
range(0, n).forEach(i -> action.run());
}
}
// streams/Looping.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import static onjava.Repeat.*;
public class Looping {
static void hi() {
System.out.println("Hi!");
}
public static void main(String[] args) {
repeat(3, () -> System.out.println("Looping!"));
// repeat(3, System.out::println);
repeat(2, Looping::hi);
}
}
/* Output:
Looping!
Looping!
Looping!
Hi!
Hi!
*/
Note that IntStream.range() is more limited than onjava.Range.range() . Because of its optional third step argument, the latter has the ability to generate ranges that step by more than one, and that can count down from a higher value to a lower one.
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/Ranges.java
3. https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#range-int-int-
4. https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#toArray--
5. https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#sum--
6. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/onjava/Repeat.java
7. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/Looping.java