<!-- Creating Primitive Streams -->
IntStream.of(int...)
IntStream.range(int, int)
IntStream.generate(IntSupplier)
IntStream.iterate(int, IntUnaryOperator)
Random.ints()
Random.ints(int, int)
<!-- Intermediate Operations on Primitive Streams -->
IntStream.flatMapToInt(ToIntFunction)
IntStream.mapToObj(IntFunction)
IntStream.boxed()
<!-- Terminal Operations on Primitive Streams -->
is.toArray();
is.min();
is.max();
is.average();
is.sum();
is.summaryStatistics();
import java.util.stream.IntStream;
class Foo {
void foo() {
IntStream.of(1, 2); // IntStream with values 1, 2
}
}
import java.util.stream.IntStream;
class Foo {
void foo() {
IntStream.range(1, 6); // IntStream with values 1, 2, 3, 4, 5
}
}
IntStream.generate(IntSupplier)
import java.util.stream.IntStream;
class Foo {
void foo() {
IntStream.generate(() -> 1); // // An infinite IntStream of 1s
}
}
IntStream.iterate(int, IntUnaryOperator)
import java.util.stream.IntStream;
class Foo {
void foo() {
IntStream.iterate(1, i -> i * 2); // An infinite IntStream of: 1, 2, 4, 8, 16...
}
}
import java.util.Random;;
class Foo {
void foo() {
final Random random = new Random();
random.ints();
}
}
import java.util.stream.Stream;
import java.util.stream.IntStream;
class Foo {
int foo;
int bar;
Foo(int foo, int bar){this.foo = foo; this.bar = bar;}
void foo() {
Stream<Foo> foo = Stream.of(new Foo(1, 2), new Foo(3, 4));
foo.flatMapToInt(f -> IntStream.of(f.foo, f.bar)); // IntStream with values: 1, 2, 3, 4
}
}
IntStream.mapToObj(IntFunction)
import java.util.stream.Stream;
import java.util.stream.IntStream;
class Foo {
int val;
Foo(int val){this.val = val;}
void foo() {
IntStream is = IntStream.rangeClosed(1, 2);
is.mapToObj(i -> new Foo(i)); // A Stream<Foo> with 2 instances: Foo[1] and Foo[2]
// Another possibility: is.mapToObj(Foo::new);
}
}
Also see: IntStream.boxed()
Method | Return Type | Reference Stream Equivalent |
---|---|---|
toArray() | int[] | |
count() | long | Stream.count() |
min() | OptionalInt | Stream.min(Comparator) |
max() | OptionalInt | Stream.max(Comparator) |
average() | OptionalDouble | Stream.collect(Collectors.averagingInt(ToIntFunction)) |
sum() | int | Stream.collect(Collectors.summingInt(ToIntFunction)) |
summaryStatistics() | IntSummaryStatistics | Stream.collect(Collectors.summarizingInt(ToIntFunction)) |
findAny() | OptionalInt | Stream.findAny() |
findFirst() | OptionalInt | Stream.findFirst() |