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]

📌 2. Mapping (Transform Each Element)

List<String> names = Arrays.asList("alice", "bob", "charlie");
List<String> uppercaseNames = names.stream()
                                   .map(String::toUpperCase)
                                   .collect(Collectors.toList());
System.out.println(uppercaseNames); // Output: [ALICE, BOB, CHARLIE]

📌 3. Sorting

List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 3);
List<Integer> sortedNumbers = numbers.stream()
                                     .sorted()
                                     .collect(Collectors.toList());
System.out.println(sortedNumbers); // Output: [1, 2, 3, 5, 8]


📌 4. Reducing (Aggregate Elements)

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().reduce(0, Integer::sum);
System.out.println(sum); // Output: 15


4️⃣ Parallel Streams (Performance Boost)

If you have a large dataset, you can use parallel streams to improve performance.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int sum = numbers.parallelStream().reduce(0, Integer::sum); System.out.println(sum); // Output: 15

5️⃣ Difference Between Stream and Collection

FeatureCollection (List, Set)Stream
StorageStores elementsDoes not store elements
ModificationCan modify elementsCannot modify original collection
IterationExternal iteration (for-loop)Internal iteration
ProcessingSequential onlySupports parallel execution


6️⃣ Summary

Streams process data efficiently using functional programming
Lazy evaluation and supports parallel execution
Does not modify the original collection





 

Comments

Popular posts from this blog

Advanced Example with Java Stream API