Java.Java8.What is stream in Java ?

✅ 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, Map
  • Arrays
  • Files, BufferedReader, Random, etc.

✅ Key Features of Streams

FeatureDescription
📍 Non-storageStreams don’t store data — they pull from a source like a list
💡 Lazy evaluationOperations are only executed when a terminal operation is called
📊 Functional styleUses lambda expressions and method references
🔁 Chainable operationsYou can compose stream methods in a pipeline
🔄 Not reusableA stream can be consumed only once

🔧 Common Stream Methods

🚿 Intermediate Operations (Lazy)

MethodDescription
.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)

MethodDescription
.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

TypeDescription
Stream<T>For object references
IntStreamSpecialized for int
LongStreamSpecialized for long
DoubleStreamSpecialized for double
parallelStream()For parallel execution

✅ Benefits of Using Streams

ProblemStream Advantage
Manual loopsReplaced by declarative, clean pipelines
Null checks and filtersUse .filter() and Optional
Data transformationUse .map(), .flatMap()
Aggregation and statsUse .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

FeatureStream in Java
💡 PurposeProcess data in functional, lazy pipelines
📦 SourceCollections, arrays, files, etc.
🔧 Core methodsmap, filter, collect, reduce, sorted
💥 Triggered byTerminal 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?
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.