Advanced Java: Streams
• Basic concepts of Java Streams
• Stream Creation
• Filter, Map, FlatMap
• Parallel Streams
• Examples for understanding
What is a Stream in Java?
• A Stream is a sequence of elements (like
objects) that supports functional-style
operations.
• Introduced in Java 8.
• Used for processing collections of data.
• Allows operations like filtering, mapping, and
reducing.
Why Use Streams?
• Simplifies complex data processing.
• Improves readability of code.
• Supports functional programming style.
• Allows easy parallel processing.
Key Features of Streams
• Streams do not store data.
• They operate on data sources like collections.
• They can be processed sequentially or in
parallel.
Java Stream Features
• The features of Java streams are mentioned
below:
• A Stream is not a data structure; it just takes
input from Collections, Arrays or I/O channels.
• Streams do not modify the original data; they
only produce results using their methods.
• Intermediate operations (like filter, map, etc.) are
lazy and return another Stream, so you can chain
them together.
• A terminal operation (like collect, forEach, count)
ends the stream and gives the final result.
Creating Streams
• Streams can be created from:
• Collections
• Arrays
• [Link]() method
• Files or input sources
Example: Stream Creation from
Collection
• List<String> names = [Link]("Ram",
"Shyam", "Amit");
• Stream<String> stream = [Link]();
Example: Stream Creation using
[Link]()
• Stream<Integer> numbers = [Link](10, 20,
30, 40);
Filter Operation
• Filter is used to select elements based on a
condition.
• It returns a new stream containing matching
elements.
Filter Example
• List<Integer> numbers = [Link](10, 15,
20, 25);
• [Link]()
• .filter(n -> n % 2 == 0)
• .forEach([Link]::println);
• Output: 10, 20
Map Operation
• Map is used to transform elements.
• Each element is converted into another form.
Map Example
• List<String> names = [Link]("ram",
"shyam");
• [Link]()
• .map(String::toUpperCase)
• .forEach([Link]::println);
• Output: RAM, SHYAM
FlatMap Operation
• FlatMap is used when each element contains
multiple values.
• It flattens nested structures into a single
stream.
FlatMap Example
• List<List<Integer>> list = [Link](
• [Link](1,2), [Link](3,4));
• [Link]()
• .flatMap(x -> [Link]())
• .forEach([Link]::println);
• Output: 1,2,3,4
Parallel Streams
• Parallel Streams divide the work across
multiple threads.
• Useful for large data processing.
• Improves performance on multicore systems.
Parallel Stream Example
• List<Integer> numbers =
[Link](1,2,3,4,5);
• [Link]()
• .forEach([Link]::println);