Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Arrays.stream()

Creates a stream from an array — for sums, filters and transformations.

Available since: Java 8

Syntax

static IntStream stream(int[] array)

Parameters

ParameterTypeDescription
arrayint[], 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
95

An 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

Related recipes

In the tutorial

  • The Arrays class — Utilities of java.util.Arrays: toString, sort, fill, copyOf, copyOfRange, equals and binarySearch.

Thanks for reading!

Donate to the site — we work hard for you.