Create streams from data
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every stream starts at a source: the place its values come from. Java can open a stream on a list, a set, an array, a few loose values, a map or a piece of text, and the steps after the source work the same way for all of them.
Streams from lists and sets
Source is where a stream gets its values: a collection, an array, a map view or text. Calling stream() on it opens a flow of those values, and the source itself is not changed.
Every collection has a stream() method, because Collection, the parent of List and Set, gives it to all of them. So list.stream() and set.stream() both work with no extra import.
Example 1 · From a list and a set
import java.util.List;import java.util.Set;import java.util.TreeSet;
public class CollectionSourcesDemo { public static void main(String[] args) { List<String> register = List.of("Kabir", "Aarav", "Diya", "Aarav", "Kabir"); System.out.println("Entries in the register: " + register.stream().count()); System.out.println("Times Aarav was marked: " + register.stream().filter(n -> n.equals("Aarav")).count());
Set<String> students = new TreeSet<>(register); System.out.println("Different students: " + students.stream().count()); System.out.println("Sorted by the TreeSet: " + students.stream().toList()); }}Entries in the register: 5 Times Aarav was marked: 2 Different students: 3 Sorted by the TreeSet: [Aarav, Diya, Kabir]
What this code does
register.stream()follows the list, duplicates included, so it counts 5 entries. The same list can be streamed again with a newstream()call.- The
TreeSetdrops the repeats and keeps names sorted, sostudents.stream()gives three names in A to Z order.
The stream follows the source's order. A List gives its values in index order. A TreeSet gives them sorted. A HashSet promises no order at all, so never rely on the order of a stream from a HashSet. A set has no duplicates, so streaming a set is a simple way to work only with different values. For example, an attendance register with repeated names becomes a TreeSet of unique students.
Streams from arrays and loose values
Arrays are not collections, so they have no stream() method. Use Arrays.stream(array) instead. Arrays.stream(array, from, to) streams only part of it: index from up to, but not including, to, like substring.
Example 2 · Arrays.stream and Stream.of
import java.util.Arrays;import java.util.List;import java.util.stream.Stream;
public class ArraySourcesDemo { public static void main(String[] args) { String[] subjects = {"Maths", "Physics", "Chemistry", "English", "Biology"};
List<String> longNames = Arrays.stream(subjects) .filter(s -> s.length() > 6) .toList(); System.out.println("Long subject names: " + longNames);
List<String> firstThree = Arrays.stream(subjects, 0, 3).toList(); System.out.println("Indexes 0 to 2: " + firstThree);
long modes = Stream.of("Card", "Cash", "Wallet").count(); System.out.println("Payment modes: " + modes);
int[] marks = {72, 45, 88}; System.out.println("Total marks: " + Arrays.stream(marks).sum()); }}Long subject names: [Physics, Chemistry, English, Biology] Indexes 0 to 2: [Maths, Physics, Chemistry] Payment modes: 3 Total marks: 205
What this code does
Arrays.stream(subjects, 0, 3)covers indexes 0, 1 and 2; the end index 3 is not included.Stream.oftakes values written straight into the code.Arrays.stream(marks)on anint[]gives anIntStream, which hassum(). AStream<String>has nosum(), because adding Strings has no meaning.
Example 3 · Stream.empty and Stream.ofNullable
import java.util.stream.Stream;
public class EmptyAndNullableDemo { static Stream<String> holidaysIn(String month) { if (month.equals("Aug")) { return Stream.of("Independence Day", "Raksha Bandhan"); } return Stream.empty(); }
public static void main(String[] args) { System.out.println("Holidays in Aug: " + holidaysIn("Aug").toList()); System.out.println("Holidays in Jul: " + holidaysIn("Jul").toList());
String coupon = "fest50"; String noCoupon = null; System.out.println("ofNullable with a value: " + Stream.ofNullable(coupon).count()); System.out.println("ofNullable with null: " + Stream.ofNullable(noCoupon).count()); System.out.println("of with null: " + Stream.of(noCoupon).count()); }}Holidays in Aug: [Independence Day, Raksha Bandhan] Holidays in Jul: [] ofNullable with a value: 1 ofNullable with null: 0 of with null: 1
What this code does
holidaysIn("Jul")returnsStream.empty()instead ofnull, so the caller can still calltoList()and simply gets[].Stream.ofNullable(noCoupon)is empty, butStream.of(noCoupon)holds onenullvalue, which crashes as soon as a later step calls a method on it.
Arrays.stream(subjects): every element of an object orintarray.Stream.of("Card", "Cash", "Wallet"): values typed in the code.Stream.empty(): no values at all.Stream.ofNullable(coupon): one value, or none when it isnull.
Stream.of(a, b, c) makes a stream from values you type directly. Stream.empty() makes a stream with no values, which is a safe thing to return when a method has nothing to give. Stream.ofNullable(x) (Java 9) gives a stream of one value, or an empty stream when x is null. An int[] array gives an IntStream, a stream of plain int values with extra methods such as sum(). The Primitive & Parallel Streams module covers it fully.
Streams from a map
A Map is not a Collection, so it has no stream() method. It has three views that are collections, and each of those can be streamed: keySet() for the keys, values() for the values and entrySet() for the key-value pairs.
Example 4 · Streams from a map
import java.util.List;import java.util.Map;import java.util.TreeMap;
public class MapSourcesDemo { public static void main(String[] args) { Map<String, Integer> feesDue = new TreeMap<>(); feesDue.put("Kabir", 4500); feesDue.put("Aarav", 0); feesDue.put("Meera", 0); feesDue.put("Diya", 12000);
List<String> reminders = feesDue.entrySet().stream() .filter(e -> e.getValue() > 0) .map(e -> e.getKey() + " owes Rs. " + e.getValue()) .toList(); System.out.println(reminders);
long cleared = feesDue.values().stream().filter(v -> v == 0).count(); System.out.println("Fees cleared: " + cleared); System.out.println("All students: " + feesDue.keySet().stream().toList()); }}[Diya owes Rs. 12000, Kabir owes Rs. 4500] Fees cleared: 2 All students: [Aarav, Diya, Kabir, Meera]
What this code does
- A map has no
stream(), so the pipeline starts fromentrySet(). Each value in the flow is one entry:filtertestsgetValue(), andmapbuilds a message from both parts. values()andkeySet()are streamed the same way when only one side is needed. TheTreeMapkeeps names sorted, so the output order never changes.
map.entrySet().stream() is the one used most. Each value in the flow is a Map.Entry, with getKey() and getValue(). That lets one step test the value, such as fees still due, and another step use the key, such as the student's name. The order again follows the map: a TreeMap gives keys in sorted order, a LinkedHashMap in the order they were added, and a HashMap in no promised order.
Streams from text
text.lines() (Java 11) splits a String at its line breaks and gives a Stream<String>, one value per line. It is handy for small reports or data pasted as text, where each line is one record.
Example 5 · Streams from text: lines and chars
import java.util.List;
public class TextSourcesDemo { public static void main(String[] args) { String report = "Aarav,72\nDiya,45\nKabir,88"; System.out.println("Rows: " + report.lines().count());
List<String> names = report.lines() .map(line -> line.split(",")[0]) .toList(); System.out.println("Names: " + names);
String word = "attendance"; long vowels = word.chars() .filter(c -> "aeiou".indexOf(c) >= 0) .count(); System.out.println("Vowels in " + word + ": " + vowels);
"Goa".chars().forEach(c -> System.out.print(c + " ")); System.out.println(); "Goa".chars().forEach(c -> System.out.print((char) c + " ")); System.out.println(); }}Rows: 3 Names: [Aarav, Diya, Kabir] Vowels in attendance: 4 71 111 97 G o a
What this code does
lines()gives one value per line, so each line of the report becomes one record thatmapcan split at the comma.chars()givesintcodes: G is 71, o is 111, a is 97.(char) cturns a code back into the letter.forEachruns an action on every value; the Terminal Operations module covers it.
text.chars() gives the characters of a String, but as an IntStream of character codes, not as char values. The letter G arrives as 71 and a as 97. Cast back with (char) c when you want to print the letter itself. Methods like Character.isDigit(c) accept the int code directly.
Trap: Stream.of with an int array
Stream.of takes any number of objects. A String[] or Integer[] is spread out into its elements, so Stream.of(names) streams every name.
Example 6 · Trap: Stream.of(intArray) has one element
import java.util.Arrays;import java.util.stream.Stream;
public class IntArrayTrapDemo { public static void main(String[] args) { int[] runs = {45, 12, 88, 30}; Integer[] boxedRuns = {45, 12, 88, 30};
System.out.println("Stream.of(int[]) count: " + Stream.of(runs).count()); System.out.println("Stream.of(Integer[]) count: " + Stream.of(boxedRuns).count()); System.out.println("Arrays.stream(int[]) count: " + Arrays.stream(runs).count()); System.out.println("Arrays.stream(int[]) sum: " + Arrays.stream(runs).sum()); }}Stream.of(int[]) count: 1 Stream.of(Integer[]) count: 4 Arrays.stream(int[]) count: 4 Arrays.stream(int[]) sum: 175
What this code does
Stream.of(runs)cannot spread anint[]into objects, so the whole array is one value: aStream<int[]>of size 1. Nothing warns you; only the count looks wrong.Integer[]holds objects, soStream.ofspreads it into four values. For anint[],Arrays.streamgives anIntStreamof all four runs.
An int[] cannot be spread out, because int is not an object type. Java treats the whole array as one object, so Stream.of(runs) is a Stream<int[]> with a single element. count() prints 1, and the code compiles without a warning. The fix is Arrays.stream(runs) or IntStream.of(45, 12, 88), which give an IntStream of the numbers.
Predict the output
How many elements?
Read the code, then pick what it prints.
Round 1 of 2
count() on an array stream prints 1, check whether a primitive array went into Stream.of.Next step
Check your understanding
12 quick questions