Explain Codes LogoExplain Codes Logo

Java 8 Stream and operation on arrays

java
stream-engineering
java-8
array-manipulation
Nikita BarsukovbyNikita Barsukov·Feb 25, 2025
TLDR
int[] array = {1, 2, 3, 4, 5}; int sum = Arrays.stream(array).sum();

By exploiting Java 8 functionality, you can readily conduct aggregate operations such as sum() on arrays, sidestepping loops altogether.

Basic stream operations on arrays

By harnessing Java 8 Streams you can quite smoothly handle arrays using lambda functions, beyond just adding them up.

Multiplying array elements

To multiply array elements by a fixed number, use map like so:

// It's like you've discovered alchemy, let's transform array with it. int[] multiplied = Arrays.stream(array).map(i -> i * 2).toArray();

Array multiplication using index

To multiply arrays element-wise, the index must come into play:

// Multiplication skills from grade school finally come handy. int[] array2 = {2, 4, 6, 8, 10}; int[] product = IntStream.range(0, array.length) .map(i -> array[i] * array2[i]) .toArray();

Stay wary of their lengths to avoid IndexOutOfBoundsException.

map vs forEach: The Showdown

In a contest of utility, forEach is only for side-effects (like displaying results), whereas map is intended for stream transformation.

// Use `forEach` to show the world your cool array. Arrays.stream(array).forEach(System.out::println); // Use `map` to create a whole new world... umm, we mean Array. int[] mappedArray = Arrays.stream(array).map(i -> i * 2).toArray();

map might be your preference considering efficiency when sifting through vast datasets.

Transforming large numbers in array

Big numbers? No worries. Use mapToLong() to escape overflow incidents:

// Size doesn't intimidate us! long largeSum = Arrays.stream(array).mapToLong(i -> (long) i).sum();

Getting Back Array

After modifying stream to your liking, repurpose it back to an array using toArray():

// Arrays were the real deal after all! int[] squares = Arrays.stream(array).map(i -> i * i).toArray();

Advanced Tips: Stream Types and Usage

A fair warning: selecting an apt stream type (IntStream, LongStream, Stream<T>) is decisive in dodging runtime mishaps and ensuring peak performance.

Object Transformation: Boxed Streams

If certain operations demand interaction with objects, like collecting to a list, you can switch to a boxed stream:

// Our array just transformed into a list, talk about metamorphosis! List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList());

Stream Efficiency Secret: IntStream.range

Get rid of your old-school for loops for improved efficiency and enhanced readability:

// We're putting a "Range" to our stream and the result is amazing. int[] squared = IntStream.range(0, array.length) .map(i -> array[i] * array[i]) .toArray();

Streams: Our Powerful Friend

Streams can unquestionably enhance code clarity and potentially increase performance, though remember understanding their trade-offs is key, like the overhead for minor operations or the complexity in parallel processing.

Visualization

Visualizing arrays and streams interplay, we can draw a metaphor with trains and stations. Each station stands for an operation the train (array) undergoes.

Array 🚂: [🎲, 🧩, 🎨, 🎮] 1. Station 🚉 (Map): Apply a function to transform each item 🎲 -> 🎰, 🧩 -> 🧸, 🎨 -> 🖼, 🎮 -> 🕹 2. Station 🚉 (Filter): Only let some items through Only even-sized toys: [🎰, 🧸] 3. Station 🚉 (Sort): Arrange items in order Smallest to largest toys: [🧸, 🎰] 4. Station 🚉 (Collect): Bring together the journey's results Final Collection: [🧸, 🎰]

Major Takeaway - Stream operations carry your data along a track, moulding and filtering it until the final output is harvested. 🚂💨🛤️

Master Level: Beyond Basic Stream Operations

Once you're skilled with the basics, it's time you scout the Java.util.Arrays new methods introduced in Java 8 to expand your horizon.

Single line for multiple operations

Multiple operations can co-occur in a single pipeline, making your code look de-cluttered:

// Turns out you can squash a lot of methods in one line with Java8, neat huh! int[] evenSquares = IntStream.range(0, array.length) .map(i -> array[i] * array[i]) .filter(i -> i % 2 == 0) .toArray();

Array manipulation: An entryway into streams

By streaming over array indices, the flexibility and power of Java 8's stream abstraction become evident, leading to elegant and comprehensible code.

References