Arrays.stream()
Creates a stream from an array — for sums, filters and transformations.
Available since: Java 8
Syntax
static IntStream stream(int[] array)Parameters
| Parameter | Type | Description |
|---|---|---|
| array | int[], T[], … | The array. There is a version with a range (startInclusive, endExclusive). |
Return value
IntStream / LongStream / DoubleStream / Stream<T>An IntStream for int[], a Stream<T> for an array of objects.
Examples
Sum, average and maximum:
void main() {
int[] scores = {72, 95, 88, 61};
IO.println(Arrays.stream(scores).sum());
IO.println(Arrays.stream(scores).average().orElse(0));
IO.println(Arrays.stream(scores).max().getAsInt());
}Output:
316
79.0
95An array of objects — filtering and mapping:
void main() {
String[] words = {"java", "is", "fun"};
List<String> result = Arrays.stream(words)
.filter(w -> w.length() > 2)
.map(String::toUpperCase)
.toList();
IO.println(result);
}Output:
[JAVA, FUN]Notes
A stream from int[] is an IntStream with its own sum(), average(), max(). average() and max() return OptionalDouble/OptionalInt, because an empty array has none. To get a List<Integer>, call .boxed().toList().
See also
- Arrays.asList() — Returns a fixed-size list backed by an array.
- Math.max() — Returns the larger of two numbers.
- Arrays.toString() — Returns the contents of an array as a string like [1, 2, 3].
Related recipes
In the tutorial
- The Arrays class — Utilities of java.util.Arrays: toString, sort, fill, copyOf, copyOfRange, equals and binarySearch.