Java Streams Explained
1️⃣ What is a Stream in Java?
A Stream in Java (introduced in Java 8) is a sequence of data elements that supports functional-style operations like filtering, mapping, and reducing. It helps in processing collections efficiently.
Key Features of Streams:
✅ Lazy Evaluation – Operations execute only when needed.
✅ Functional Programming – Uses lambda expressions.
✅ Parallel Processing – Supports parallel execution for better performance.
✅ Immutability – Does not modify the original collection.
2️⃣ How to Create a Stream?
📌 Creating Streams from Collections
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Stream<String> stream = names.stream();
📌Creating Streams from Arrays
Stream<String> stream = Stream.of("Apple", "Banana", "Cherry");
3️⃣ Common Stream Operations
📌 1. Filtering (Filter Elements Based on Condition)
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers); // Output: [2, 4]
If you have a large dataset, you can use parallel streams to improve performance.
5️⃣ Difference Between Stream and Collection
| Feature | Collection (List, Set) | Stream |
|---|---|---|
| Storage | Stores elements | Does not store elements |
| Modification | Can modify elements | Cannot modify original collection |
| Iteration | External iteration (for-loop) | Internal iteration |
| Processing | Sequential only | Supports parallel execution |
6️⃣ Summary
✔ Streams process data efficiently using functional programming
✔ Lazy evaluation and supports parallel execution
✔ Does not modify the original collection
Comments
Post a Comment