Java.Core.What are Java Streams, and how are they used?

☕️ What are Java Streams?

Java Streams are part of the java.util.stream package.
✅ They provide a functional-style way to process sequences of elements (like collections, arrays, files, etc.) in a declarative manner.


🔗 Key Points

What it isExplanation
StreamA sequence of data elements (from a collection, array, or I/O source) that can be processed in a pipeline.
PipelineA series of steps where data flows through transformations (filters, maps, etc.) and ends with a result (a collection, sum, or side effect).
FunctionalEncourages writing what to do, not how to do it (declarative style).
One-time useStreams cannot be reused — once consumed, they are gone.

📦 How to Create a Stream

Example – from a List

List<String> names = List.of("Alice", "Bob", "Charlie");
Stream<String> stream = names.stream();

🛠️ Common Stream Operations

TypeExamplesExplanation
Creationstream(), Stream.of()Create a stream from data sources
Intermediatefilter(), map(), sorted()Transform the stream (lazy)
Terminalcollect(), forEach(), count()Final result (triggers processing)

🌊 Example – Complete Stream Pipeline

List<String> names = List.of("Alice", "Bob", "Charlie");

List<String> filteredNames = names.stream()
        .filter(name -> name.startsWith("A"))   // Intermediate
        .map(String::toUpperCase)                // Intermediate
        .sorted()                                // Intermediate
        .collect(Collectors.toList());           // Terminal

System.out.println(filteredNames);  // [ALICE]

✅ Processing is lazy — nothing happens until a terminal operation (collect()) is called.
✅ This is a pipeline: Source ➡️ Filter ➡️ Map ➡️ Sort ➡️ Collect.

💨 Streams vs Collections

AspectCollectionStream
StorageStores dataDoes not store data
ReuseCan be iterated many timesCan be consumed only once
Eager/LazyProcessing is eager (immediate)Processing is lazy (only happens when terminal operation is called)
External/Internal iterationYou iterate manually (for loop)Stream handles iteration internally

⚙️ Parallel Streams

Streams can also run in parallel to leverage multi-core processors.

List<String> names = List.of("Alice", "Bob", "Charlie");

long count = names.parallelStream()
        .filter(name -> name.startsWith("A"))
        .count();

✅ Each operation may run in a different thread, improving performance on large datasets.

💥 Common Use Cases

Use CaseExample
Filter dataNames starting with “A”
Transform dataConvert all names to uppercase
AggregationSum of all prices
Collecting resultConvert stream back to List/Set/Map

🚨 Key Things to Remember

Stream ≠ Collection — it’s a view, not storage.
One-time use — you cannot reuse a stream.
Lazy evaluation — intermediate steps only run if a terminal operation is present.
Functional-style — write what to do, not how to do it.


🚀 Quick Recap

StepExample
Create Streamlist.stream()
Intermediate opsfilter(), map()
Terminal opcollect(), count()
This entry was posted in Без рубрики. Bookmark the permalink.