Sub topic 4
Creating Streams from Collections, Arrays, and Values
Every stream pipeline begins with a source. A source is the place the elements come from. You saw in the last chapter that a pipeline has three parts: a source, intermediate operations, and a terminal operation. This chapter covers only the first part. You will learn the common ways to make a stream and a few traps that catch beginners.
You need Java 9 or later to run the examples, because they use List.of, Set.of, and Map.of to build small collections quickly.
Why the Source Matters
A stream does not store data. It reads elements from its source, one at a time, when a terminal operation asks for them. The source affects three things:
- The element type. A
List<String>gives you aStream<String>. - The order. A
Listkeeps its order, but aHashSetorSet.ofhas no fixed order. - What happens to the original data. Nothing. A stream never changes its source. Operations like
filterproduce new results and leave the list or array as it was.
Streams from Collections
A collection is an object that holds a group of elements, such as a List or a Set. Every collection has a method called stream(), which returns a stream over its elements.
A Map is not a collection in Java, so it has no stream() method. A map stores entries, and each entry is a key paired with a value. To stream a map, pick one of its three views first:
map.keySet().stream()streams the keys.map.values().stream()streams the values.map.entrySet().stream()streams the entries. Each entry hasgetKey()andgetValue().
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class CollectionSources {
public static void main(String[] args) {
// A List keeps its order
List<String> colors = List.of("red", "green", "blue");
List<String> copy = colors.stream()
.collect(Collectors.toList());
System.out.println(copy); // [red, green, blue]
// A Set works the same way, but its order is not guaranteed
Set<Integer> ids = Set.of(7, 3, 9);
System.out.println(ids.stream().count()); // 3
// A Map needs a view first: keySet, values, or entrySet
Map<String, Integer> ages = Map.of("Ann", 31, "Ben", 25);
long over30 = ages.entrySet().stream()
.filter(entry -> entry.getValue() > 30)
.count();
System.out.println(over30); // 1
int totalAge = ages.values().stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println(totalAge); // 56
}
}collect(Collectors.toList()) gathers the elements into a new list, and count() counts them. Both are terminal operations, and later chapters cover them in detail. mapToInt turns the values into plain numbers so that sum() can add them. A later chapter covers that too.
Streams from Arrays
An array is a fixed-size block of elements, such as String[]. Arrays do not have a stream() method. Use the helper class java.util.Arrays instead:
Arrays.stream(array)streams the whole array.Arrays.stream(array, from, to)streams part of it. Thefromindex is included and thetoindex is not.
For arrays of objects, Stream.of(array) also works.
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ArraySources {
public static void main(String[] args) {
String[] fruits = {"apple", "banana", "cherry", "date"};
System.out.println(Arrays.stream(fruits)
.collect(Collectors.toList())); // [apple, banana, cherry, date]
// Indexes 1 and 2 only (3 is excluded)
System.out.println(Arrays.stream(fruits, 1, 3)
.collect(Collectors.toList())); // [banana, cherry]
System.out.println(Stream.of(fruits).count()); // 4
}
}Streams from Individual Values
Sometimes your values are not in any collection or array. Stream.of(...) takes any number of values and makes a stream from them. You can also make a stream with no elements at all.
Stream.of(a, b, c)makes a stream of the values you list.Stream.empty()makes a stream with zero elements. It is a safe thing to return from a method that has nothing to give back. Unlikenull, it will not cause aNullPointerExceptionlater.Stream.builder()lets you add elements one by one and then callbuild(). This helps when you decide what to add withifstatements.
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ValueSources {
public static void main(String[] args) {
Stream<String> letters = Stream.of("x", "y", "z");
System.out.println(letters.collect(Collectors.toList())); // [x, y, z]
Stream<String> nothing = Stream.empty();
System.out.println(nothing.count()); // 0
boolean includeBonus = true;
Stream.Builder<String> builder = Stream.builder();
builder.add("one");
builder.add("two");
if (includeBonus) {
builder.add("bonus");
}
Stream<String> built = builder.build();
System.out.println(built.collect(Collectors.toList())); // [one, two, bonus]
}
}The Primitive Array Trap
A primitive type is a basic value type that is not an object, such as int, long, or double. Primitive arrays like int[] behave in a surprising way with Stream.of.
Stream.of expects objects. An int is not an object, but an int[] is. So Stream.of(nums) treats the whole array as one element and gives you a Stream<int[]> with a single item. Arrays.stream(nums) does what you want: it gives a stream of the three numbers.
import java.util.Arrays;
import java.util.stream.Stream;
public class PrimitiveArrayTrap {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
System.out.println(Stream.of(nums).count()); // 1 (one int[] element)
System.out.println(Arrays.stream(nums).count()); // 3 (three int values)
Integer[] boxed = {1, 2, 3};
System.out.println(Stream.of(boxed).count()); // 3 (Integer is an object)
}
}Arrays.stream(nums) actually returns an IntStream, a special stream made for int values. The chapter on primitive streams explains these.
Quick Reference
| You have | Write | You get |
|---|---|---|
| `List<T>` or `Set<T>` | `collection.stream()` | `Stream<T>` |
| `Map<K, V>` | `map.entrySet().stream()` | `Stream<Map.Entry<K, V>>` |
| `T[]` (objects) | `Arrays.stream(arr)` or `Stream.of(arr)` | `Stream<T>` |
| `int[]` | `Arrays.stream(arr)` | `IntStream` |
| Part of an array | `Arrays.stream(arr, from, to)` | Elements from `from` up to `to - 1` |
| A few values | `Stream.of(a, b, c)` | `Stream<T>` |
| No values | `Stream.empty()` | Empty stream |
Edge Cases to Remember
- Null source. Calling
stream()on anulllist throws aNullPointerException. Check for null first, or returnStream.empty()instead. - Empty source. An empty list gives an empty stream. That is fine:
count()returns0andcollectreturns an empty list. - Set order. Do not rely on the order of elements from
Set.oforHashSet. Use aList, aTreeSet, or sort the stream if order matters. - One use only. Each call to
stream()makes a new stream. A single stream can be used only once, so calllist.stream()again for a second pipeline. - Other sources. Some sources make a stream that never ends, such as
Stream.iterateandStream.generate. A later chapter covers those.
Exercise
You have String[] words = {"sun", "moon", "star", "sky"};. Write one expression that streams only "moon" and "star" and counts them.
Show answer
Arrays.stream(words, 1, 3).count() returns 2. Index 1 is "moon", index 2 is "star", and index 3 is excluded.
Exercise
Why does Stream.of(new int[]{4, 5, 6}).count() print 1 instead of 3, and how do you fix it?
Show answer
Stream.of needs objects, so it treats the whole int[] as a single element and makes a Stream<int[]>. Use Arrays.stream(new int[]{4, 5, 6}).count(), which streams the three int values and returns 3.
Exercise
Given Map<String, Integer> stock = Map.of("pens", 0, "cups", 12, "pads", 5);, write a pipeline that counts how many items have a stock greater than 0.
Show answer
stock.entrySet().stream().filter(e -> e.getValue() > 0).count() returns 2. You could also write stock.values().stream().filter(v -> v > 0).count(), since only the values matter here.