0% found this document useful (0 votes)
15 views11 pages

Mastering The Stream API in Java

Uploaded by

selfsatyam07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views11 pages

Mastering The Stream API in Java

Uploaded by

selfsatyam07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Mas tering S tream AP I

in Java
Unlock modern, functional data processing
Stream API

Introduced in Java 8 Data Pipeline


Revolutionized collection handling and data A sequence of elements from a source (collections,
processing. arrays, etc.).

Functional Style Processes Data


Supports declarative, concise operations on data. Does not store data; it processes elements from its
source.
Divers e S tream Creation Methods
From Collections & Arrays Static Factories & Generators

List<String> list = Arrays.asList("A", "B"); Stream<String> s = Stream.of("Java", "Python");


Stream<String> stream = list.stream();
Stream<Double> randoms = Stream.generate(Math::random).limit(5);

int[] numbers = {1, 2, 3};


IntStream numStream = Arrays.stream(numbers); Stream<Integer> evens = Stream.iterate(0, n -> n + 2).limit(5);

The most common way: leverage existing data structures directly.


For arbitrary data or infinite sequences, with a limit() for finite results.

Streams can be generated from almost anywhere – collections, arrays or even infinite generators, providing immense
flexibility for various data sources.
Stream Operations: The Pipeline

Intermediate Operations
Transform the stream: These operations are lazy and return a new Stream.
They build the pipeline without processing data until a terminal operation is called.

• filter(): Select elements based on a predicate.

• map(): Transform elements to a new type.

• sorted(): Sort elements.

• distinct(): Remove duplicates.

• limit(), skip(): Control stream size.

Terminal Operations
Produce the result: These operations are eager and consume the stream, triggering all
intermediate operations. They produce a non-stream result.

• collect(): Accumulate elements into a collection.

• forEach(): Perform an action for each element.

• reduce(): Combine elements into a single result.

• count(): Return the number of elements.

• anyMatch(): Check if any element matches.


Intermediate Operations in Action: Filter & Map

List<String> names = Arrays.asList("John", "Jane", "Mike", "Sam");


Output:
names.stream().filter(n -> n.startsWith("J")) // Keeps "John", "Jane"
JOHN JANE
.map(String::toUpperCase) // Transforms to "JOHN", "JANE"
.forEach(System.out::println); // prints JOHN JANE

This pipeline efficiently filters names starting with 'J' and then transforms them to uppercase.
Intermediate operations are lazy – they only execute when a terminal operation like forEach() is invoked
Advanced Intermediate Chaining

List<Integer> numbers = Arrays.asList(5, 2, 3, 2, 8, 5, 9); Output:


numbers.stream().distinct()// Removes duplicate 2s, 5s -> [5, 2, 3, 8, 9]
.sorted() // Sorts elements -> [2, 3, 5, 8, 9]
3 5 8
.skip(1) // Skips the first element (2) -> [3, 5, 8, 9]
.limit(3) // Takes the next 3 elements -> [3, 5, 8]
.forEach(System.out::println); // prints 3 5 8

Observe how multiple intermediate operations can be chained together to create expressive data transformation pipelines.
Each step refines the stream, leading to a precise final result.
Terminal Operations : Getting Res ults

forEach()

1 list.stream().forEach(System.out::println);

Performs an action for each element. No return value.

collect()

2 Set<String> set = list.stream().collect(Collectors.toSet());

Gathers elements into a new collection or summary. Highly versatile.

reduce()

3 int sum = numbers.stream().reduce(0, (a, b) -> a + b);

Aggregates elements into a single result (e.g., sum, max, min).

count() & Matchers

4 long count = list.stream().count();


boolean hasEven = numbers.stream().anyMatch(n -> n % 2 == 0);

Counts elements or checks if elements satisfy a predicate.


Real-World Application: Employee Data Proces s ing
class Employee {
String name; Output:
int age;
double salary;
[Alice, Bob]

Employee(String name, int age, double salary) {


this.name = name;
this.age = age;
this.salary = salary; • This example demonstrates how Stream API simplifies
} complex data manipulation.
}
List<Employee> employees = Arrays.asList( • We concisely filter for employees earning over 50,000,
new Employee("John", 25, 50000), extract their names, and collect them into a new list.
new Employee("Alice", 30, 60000),
new Employee("Bob", 35, 70000), • This replaces many lines of imperative loop-based code with
new Employee("Sam", 28, 45000) a single, readable pipeline.
);
List<String> highEarners = employees.stream()
.filter(e -> e.salary > 50000)
.map(e -> e.name)
.collect(Collectors.toList());

System.out.println(highEarners);
K ey B enefits of Embracing S treams

Concis e & Declarative Functional P aradigm Efficient Data P roces s ing


Write less code, focusing on Aligns with modern functional Optimized for processing large
"what" to do rather than "how" to programming principles, datasets with minimal overhead.
do it. promoting purity.

P arallel P roces s ing Reduces B oilerplate


Easily leverage multi-core processors with Eliminates verbose loops and conditional statements.
parallelStream() for enhanced performance.
Recap & Next Steps

What is Stream API?


A functional pipeline for processing data sequences.

Creating Streams
From collections, arrays, Stream.of(), generators.

Intermediate Operations
Lazy transformations that build the pipeline (e.g., filter, map).

Terminal Operations
Trigger execution and produce results (e.g., collect, forEach).

The Stream API, combined with Lambda Expressions, provides a modern,


expressive, and highly efficient way to process data in Java.

You might also like