Sub topic 13
Processing Arrays with Streams
A stream is a way to process a sequence of values through a series of steps. For an array, those steps might select some elements, change the selected values, and collect the results.
Streams can make a task easier to read when you want to describe what happens to the values. They do not change the original array unless your code explicitly does so.
This chapter assumes you know how to create arrays and use basic methods and loops. The examples use Java 8 or later.
From an array to a result
A stream pipeline is a series of steps that processes data. It has three parts:
- A source supplies the values. Here, the source is an array.
- Intermediate operations prepare the values. An operation is a processing step. For example,
filterkeeps values that pass a test. - A terminal operation finishes the pipeline and produces a result or performs an action.
A worked example
Save this program in a file named StreamScores.java.
import java.util.Arrays;
public class StreamScores {
public static void main(String[] args) {
int[] scores = {80, 90, 100, 65};
int[] adjusted = Arrays.stream(scores)
.filter(score -> score >= 80)
.map(score -> score + 5)
.toArray();
System.out.println("Adjusted: " + Arrays.toString(adjusted));
System.out.println("Original: " + Arrays.toString(scores));
}
}Compile and run it from the folder containing the file:
javac StreamScores.java
java StreamScoresThe first line of output is Adjusted: [85, 95, 105]. The second is Original: [80, 90, 100, 65].
Here is what each step does:
Arrays.stream(scores)creates a stream from the array. Because the array containsintvalues, Java creates anIntStream, a stream for whole-numberintvalues.filter(score -> score >= 80)keeps values that are at least 80. The value 65 does not pass the test.map(score -> score + 5)makes a new value for each value that remains.toArray()collects those new values in a newintarray.
The expressions inside filter and map are lambdas. A lambda is a short way to describe an action or calculation. In score -> score + 5, score is the name for a value being processed, and the part after -> says what to do with it. You can choose a different name, such as value.
Arrays.toString makes a readable text version of each array for printing. It does not change either array.
Choose operations for the result
You can combine operations to suit the task. The table shows common choices for an IntStream.
| Operation | What it does |
|---|---|
| `filter` | Keeps values that pass a test. |
| `map` | Produces a new value from each value. |
| `distinct` | Keeps one of each value. |
| `sorted` | Puts the stream values in order. |
| `count` | Finishes the stream and counts its values. |
| `sum` | Finishes the stream and adds its values. |
| `average` | Finishes the stream and finds the mean. |
| `toArray` | Finishes the stream and collects values in a new array. |
| `forEach` | Finishes the stream and performs an action for each value. |
The first four are intermediate operations. They prepare a stream for the next step. The rest are terminal operations.
The order of steps matters. With the scores 80, 90, 100, 65:
- Filtering for values at least 85 and then adding 5 produces
95, 105. - Adding 5 first and then filtering for values at least 85 produces
85, 95, 105.
In the second case, 80 becomes 85 before the test, so it passes.
Count, sum, and average
Some terminal operations produce one number instead of an array. Save this example as ScoreSummary.java, then compile and run it as you did the first program.
import java.util.Arrays;
public class ScoreSummary {
public static void main(String[] args) {
int[] scores = {80, 90, 100, 65};
long passingCount = Arrays.stream(scores)
.filter(score -> score >= 70)
.count();
int total = Arrays.stream(scores).sum();
double passingAverage = Arrays.stream(scores)
.filter(score -> score >= 70)
.average()
.orElse(0.0);
double missingAverage = Arrays.stream(scores)
.filter(score -> score > 100)
.average()
.orElse(0.0);
System.out.println("Passing count: " + passingCount);
System.out.println("Total: " + total);
System.out.println("Passing average: " + passingAverage);
System.out.println("Missing average: " + missingAverage);
}
}The program prints a passing count of 3, a total of 335, and a passing average of 90.0. It prints 0.0 for the missing average because no score is greater than 100.
The count method returns a long, a whole-number type that can hold larger values than int. For an IntStream, sum returns an int. If the total is too large for an int, it can overflow, which means the result is no longer the correct total. For totals that need more room, use asLongStream() before sum().
The average method returns an OptionalDouble. This is an object that may hold a double value, a number that can have a decimal part. It may also be empty, because an empty stream has no average. The call orElse(0.0) supplies 0.0 when there is no average. Choose that fallback carefully: a missing average is not always the same thing as a real average of zero.
Streams of strings
Arrays.stream also works with arrays of objects, such as strings. The next program filters names, changes them to uppercase, and prints them in order.
Save it as StreamNames.java, then compile and run it.
import java.util.Arrays;
import java.util.Locale;
public class StreamNames {
public static void main(String[] args) {
String[] names = {"Ada", null, "Li", "Lin", "Mira"};
Arrays.stream(names)
.filter(name -> name != null)
.filter(name -> name.length() >= 3)
.map(name -> name.toUpperCase(Locale.ROOT))
.sorted()
.forEach(name -> System.out.println(name));
}
}The program prints ADA, LIN, and MIRA, each on its own line.
The first filter removes null, which means no object is present. This matters because calling length() on null would cause an error. The next filter keeps names with at least three characters.
The map step creates uppercase strings. Locale.ROOT tells Java to use language-independent rules for this conversion. Then sorted orders the stream values. It does not sort the names array.
Finally, forEach prints each value. These examples use sequential streams, which process the values without splitting the work across multiple threads. A thread is a path of work a program can run. For this sequential example, forEach prints the sorted values in order.
Avoid common mistakes
Finish the pipeline
Intermediate operations are lazy: they describe work but do not start processing the values by themselves. A terminal operation starts that work.
For example, creating a stream and adding a filter does not print anything or produce a filtered array. Add a terminal operation such as count, toArray, or forEach to get a result.
Create a fresh stream for each result
A stream can be used for only one terminal operation. Trying to use the same stream again after it has finished causes an IllegalStateException, an error that means the stream is no longer in a usable state.
The summary example avoids this problem by calling Arrays.stream(scores) again for each result. Each call creates a fresh stream from the same array.
Keep source changes separate
Operations such as filter, map, and sorted do not update the source array. If you need the result later, collect it with a terminal operation, as the first example does with toArray(), and store the returned array.
Exercise
An array holds 4, 7, and 10. A stream filters for values greater than 5, then maps each remaining value to that value times 2. What does toArray() collect?
Show answer
It collects 14 and 20 in a new array. The value 4 does not pass the filter.
Exercise
Why does the summary program call Arrays.stream(scores) separately for the count and the sum?
Show answer
Each terminal operation finishes its stream. A fresh stream is needed for the next terminal operation.
Exercise
What happens if average() is called after a filter that keeps no values, and the result uses orElse(0.0)?
Show answer
The average is empty, so orElse(0.0) supplies 0.0. That does not mean the empty stream had a real average of zero.