✅ What is a Stream in Java?
A Stream is a sequence of elements that supports functional-style operations to process data.
You can think of a Stream as a pipeline of data that flows through map/filter/collect operations — without modifying the original source (like a list or array).
📦 Where does it live?
import java.util.stream.Stream;
You can also create them from:
List, Set, MapArrays Files, BufferedReader, Random, etc.
✅ Key Features of Streams
Feature Description 📍 Non-storage Streams don’t store data — they pull from a source like a list 💡 Lazy evaluation Operations are only executed when a terminal operation is called 📊 Functional style Uses lambda expressions and method references 🔁 Chainable operations You can compose stream methods in a pipeline 🔄 Not reusable A stream can be consumed only once
🔧 Common Stream Methods
🚿 Intermediate Operations (Lazy)
Method Description .map()Transform each element .filter()Keep only matching elements .sorted()Sort the stream .limit(n)Take first n elements .distinct()Remove duplicates
💧 Terminal Operations (Trigger the stream)
Method Description .forEach()Apply an action to each element .collect()Gather results (e.g. into a list) .reduce()Reduce stream to a single result .count()Count elements .findFirst()Get first matching element (Optional) .anyMatch()Returns true if any match predicate
🧠 Example: Filter, Map, and Collect
List<String> names = List.of("Alice", "Bob", "Charlie");
List<String> uppercased = names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(uppercased); // Output: [ALICE, CHARLIE]
🔁 Stream Types
Type Description Stream<T>For object references IntStreamSpecialized for int LongStreamSpecialized for long DoubleStreamSpecialized for double parallelStream()For parallel execution
✅ Benefits of Using Streams
Problem Stream Advantage Manual loops Replaced by declarative, clean pipelines Null checks and filters Use .filter() and Optional Data transformation Use .map(), .flatMap() Aggregation and stats Use .collect(), .reduce(), .summaryStatistics()
⚠️ Important Tips
✅ Streams are not collections — they don’t store data ❌ You can’t reuse a stream once it’s been consumed ✅ Use lazy operations to build logic without side effects ❌ Avoid using stream().forEach(...) for mutation — prefer map() and collect()
✅ Summary
Feature Stream in Java💡 Purpose Process data in functional, lazy pipelines 📦 Source Collections, arrays, files, etc. 🔧 Core methods map, filter, collect, reduce, sorted💥 Triggered by Terminal operations like forEach, collect
Let me know if you’d like:
Real-world coding challenges using Stream Practice converting loops into streams Or a comparison: Stream vs for loop vs Iterator?