Java Stream API
1. What is the Stream API?
Introduced in Java 8, the Stream API is used to process collections
(like Lists, Sets) in a declarative way.
The Java Stream API provides a functional approach to process the
collections of data. It allows for efficient and readable operations such
as filtering, mapping, and reducing elements.
It supports functional-style operations like filtering, mapping,
reducing, and sorting.
2. Stream API Basics
A Stream represents a sequence of elements that supports various
operations to process data efficiently.
Creating a Stream
import [Link];
import [Link];
import [Link];
public class StreamExample {
public static void main(String[] args) {
// Creating a stream from a list
List<String> names = [Link]("Annie",
"Bobby","Carl", "David");
Stream<String> namesStream = [Link]();
// Creating a stream directly
Stream<String> directStream=
[Link]("Apple","Banana","Cherry");
// Creating a stream from an array
String[] fruits = {"Mango", "Orange", "Grapes"};
Stream<String> arrayStream = [Link](fruits);
}
}
3. Common Stream Operations
a) Filtering Elements (filter())
Filters elements based on a condition.
import [Link];
import [Link];
import [Link];
public class FilterExample {
public static void main(String[] args) {
List<String> names=[Link]("Annie",
"Bobby","Carl","Anna", "David");
// Get names starting with "A"
List<String> filteredNames=[Link]()
.filter(name-
>[Link]("A"))
.collect([Link]());
[Link](filteredNames);
}
}
// Output: [Annie, Anna]
b) Transforming Elements (map())
Applies a function to each element and transforms the data.
import [Link];
import [Link];
import [Link];
public class MapExample {
public static void main(String[] args) {
List<String> names = [Link]("Annie",
"Bobby","Carl","David");
// Convert names to uppercase
List<String> upperCaseNames = [Link]()
.map(String::toUpperCase)
.collect([Link]()
);
[Link](upperCaseNames);
}
}
// Output: [ANNIE, BOBBY, CARL, DAVID]
c) Sorting Elements (sorted())
Sorts elements in ascending or custom order.
import [Link];
import [Link];
import [Link];
public class SortingExample {
public static void main(String[] args) {
List<Integer> numbers = [Link](5, 3, 8, 11, 1, 9);
// Sort in ascending order
List<Integer> sortedNums = [Link]()
.sorted()
.collect([Link]
t());
[Link](sortedNums);
}
}
// Output: [1, 3, 5, 8, 9, 11]
d) Finding and Matching (anyMatch(), allMatch(),
findFirst())
Checks if elements match a condition.
import [Link];
import [Link];
public class MatchingExample {
public static void main(String[] args) {
List<String> name = [Link]("Annie",
"Bobby","Carl", "David");
boolean anyStartsWithA = [Link]().anyMatch(name ->
[Link]("A"));
boolean allStartsWithA = [Link]().allMatch(name ->
[Link]("A"));
[Link](anyStartsWithA);
[Link](allStartsWithA);
}
}
// Output: true
// Output: false
e) Reducing Elements (reduce())
Aggregates stream elements to a single value.
import [Link];
import [Link];
public class ReduceExample {
public static void main(String[] args) {
List<Integer> nums = [Link](1, 2, 3, 4, 5);
// Sum of all numbers
int addition = [Link]().reduce(0, Integer::sum);
[Link](addition);
}
}
// Output: 15
f) Collecting Results (collect())
Converts stream data into a collection.
import [Link];
import [Link];
import [Link];
public class CollectExample {
public static void main(String[] args) {
List<String> names = [Link]("Annie",
"Bobby","Carl","David");
// Convert names to a comma-separated string
String result =
[Link]().collect([Link](", "));
[Link](result);
}
}
// Output: Annie, Bobby, Carl, David
4. Parallel Streams (for performance)
Parallel streams process elements concurrently for large datasets.
import [Link];
import [Link];
public class ParallelStreamExample {
public static void main(String[] args) {
List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6,
7);
// Using parallel stream for faster processing
int addition = [Link]().reduce(0,
Integer::sum);
[Link](addition);
}
}
// Output: 28
5. Stream vs. Regular Loop
Feature Stream API Traditional Loop
Readability More readable and declarative More verbose
Performan Can use parallel processing Sequential execution
ce
Flexibility Easily combined with multiple Requires nested loops
operations
Modifiabilit Operations are chainable Manual modifications
y required
6. Summary
Stream API simplifies operations on collections
Supports functional programming
Uses lazy evaluation for efficiency
Can be parallelized for better performance
Filtering (filter())
Transforming (map())
Sorting (sorted())
Finding (findFirst(), max(), min())
Grouping (groupingBy())
Reducing (reduce())