| name | java-streams-api |
| user-invocable | false |
| description | Use when Java Streams API for functional-style data processing. Use when processing collections with streams. |
| allowed-tools | ["Bash","Read","Write","Edit"] |
Java Streams API
Master Java's Streams API for functional-style operations on collections,
enabling declarative data processing with operations like filter, map, and
reduce.
Introduction to Streams
Streams provide a functional approach to processing collections of objects.
Unlike collections, streams don't store elements - they convey elements from
a source through a pipeline of operations.
Creating streams:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class StreamCreation {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream1 = list.stream();
String[] array = {"a", "b", "c"};
Stream<String> stream2 = Arrays.stream(array);
Stream<String> stream3 = Stream.of("a", "b", "c");
Stream<String> stream4 = Stream.empty();
Stream<Integer> stream5 = Stream.iterate(0, n -> n + 1)
.limit(10);
}
}
Intermediate Operations
Intermediate operations return a new stream and are lazy - they don't
execute until a terminal operation is invoked.
filter() - Select elements:
import java.util.List;
import java.util.stream.Collectors;
public class FilterExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
List<Integer> result = numbers.stream()
.filter(n -> n > 3)
.filter(n -> n < 7)
.collect(Collectors.toList());
}
}
map() - Transform elements:
public class MapExample {
public static void main(String[] args) {
List<String> words = List.of("hello", "world");
List<String> uppercase = words.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
List<Integer> lengths = words.stream()
.map(String::length)
.collect(Collectors.toList());
List<Integer> doubled = List.of(1, 2, 3).stream()
.map(n -> n * 2)
.collect(Collectors.toList());
}
}
flatMap() - Flatten nested structures:
public class FlatMapExample {
public static void main(String[] args) {
List<List<Integer>> nested = List.of(
List.of(1, 2),
List.of(3, 4),
List.of(5, 6)
);
List<Integer> flattened = nested.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
List<String> sentences = List.of("hello world", "foo bar");
List<String> words = sentences.stream()
.flatMap(s -> Arrays.stream(s.split(" ")))
.collect(Collectors.toList());
}
}
distinct() and sorted():
public class DistinctSortedExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(5, 2, 8, 2, 1, 5, 3);
List<Integer> distinct = numbers.stream()
.distinct()
.collect(Collectors.toList());
List<Integer> sorted = numbers.stream()
.sorted()
.collect(Collectors.toList());
List<Integer> descending = numbers.stream()
.sorted((a, b) -> b - a)
.collect(Collectors.toList());
List<Integer> distinctSorted = numbers.stream()
.distinct()
.sorted()
.collect(Collectors.toList());
}
}
peek() - Debug or perform side effects:
public class PeekExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
List<Integer> result = numbers.stream()
.peek(n -> System.out.println("Original: " + n))
.map(n -> n * 2)
.peek(n -> System.out.println("Doubled: " + n))
.filter(n -> n > 5)
.peek(n -> System.out.println("Filtered: " + n))
.collect(Collectors.toList());
}
}
Terminal Operations
Terminal operations produce a result or side effect and close the stream.
collect() - Gather results:
import java.util.stream.Collectors;
import java.util.Map;
import java.util.Set;
public class CollectExample {
public static void main(String[] args) {
List<String> words = List.of("apple", "banana", "cherry");
List<String> list = words.stream()
.collect(Collectors.toList());
Set<String> set = words.stream()
.collect(Collectors.toSet());
Map<String, Integer> map = words.stream()
.collect(Collectors.toMap(
w -> w,
String::length
));
String joined = words.stream()
.collect(Collectors.joining(", "));
Map<Integer, List<String>> grouped = words.stream()
.collect(Collectors.groupingBy(String::length));
}
}
reduce() - Combine elements:
public class ReduceExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
int product = numbers.stream()
.reduce(1, (a, b) -> a * b);
Optional<Integer> max = numbers.stream()
.reduce((a, b) -> a > b ? a : b);
int sum2 = numbers.stream()
.reduce(0, Integer::sum);
String concatenated = List.of("a", "b", "c").stream()
.reduce("", (a, b) -> a + b);
}
}
forEach() and forEachOrdered():
public class ForEachExample {
public static void main(String[] args) {
List<String> words = List.of("hello", "world");
words.stream()
.forEach(System.out::println);
words.parallelStream()
.forEachOrdered(System.out::println);
List<String> results = new ArrayList<>();
words.stream()
.map(String::toUpperCase)
.forEach(results::add);
}
}
count(), anyMatch(), allMatch(), noneMatch():
public class MatchingExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
long count = numbers.stream()
.filter(n -> n > 2)
.count();
boolean hasEven = numbers.stream()
.anyMatch(n -> n % 2 == 0);
boolean allPositive = numbers.stream()
.allMatch(n -> n > 0);
boolean noNegative = numbers.stream()
.noneMatch(n -> n < 0);
}
}
findFirst() and findAny():
public class FindExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
Optional<Integer> first = numbers.stream()
.filter(n -> n > 2)
.findFirst();
Optional<Integer> any = numbers.parallelStream()
.filter(n -> n > 2)
.findAny();
Integer value = numbers.stream()
.filter(n -> n > 10)
.findFirst()
.orElse(-1);
}
}
Advanced Collectors
Partitioning and grouping:
public class AdvancedCollectors {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
Map<Integer, Long> lengthCounts = List.of("a", "bb", "ccc").stream()
.collect(Collectors.groupingBy(
String::length,
Collectors.counting()
));
Map<Integer, List<String>> grouped =
List.of("apple", "apricot", "banana").stream()
.collect(Collectors.groupingBy(
String::length,
Collectors.mapping(
String::toUpperCase,
Collectors.toList()
)
));
}
}
Statistics collectors:
import java.util.IntSummaryStatistics;
import java.util.stream.Collectors;
public class StatisticsExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
IntSummaryStatistics stats = numbers.stream()
.collect(Collectors.summarizingInt(Integer::intValue));
System.out.println("Count: " + stats.getCount());
System.out.println("Sum: " + stats.getSum());
System.out.println("Min: " + stats.getMin());
System.out.println("Max: " + stats.getMax());
System.out.println("Average: " + stats.getAverage());
double average = numbers.stream()
.collect(Collectors.averagingInt(Integer::intValue));
}
}
Parallel Streams
Parallel streams automatically partition data and process in parallel.
Using parallel streams:
public class ParallelStreamExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8);
int sum = numbers.parallelStream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
long count = numbers.stream()
.parallel()
.filter(n -> n > 3)
.count();
boolean isParallel = numbers.parallelStream().isParallel();
List<Integer> result = numbers.parallelStream()
.sequential()
.collect(Collectors.toList());
}
}
Performance considerations:
import java.util.stream.IntStream;
public class ParallelPerformance {
public static void main(String[] args) {
List<Integer> small = IntStream.range(0, 100)
.boxed()
.collect(Collectors.toList());
List<Integer> large = IntStream.range(0, 1_000_000)
.boxed()
.collect(Collectors.toList());
long start = System.nanoTime();
long sum1 = large.stream()
.mapToLong(Integer::longValue)
.sum();
long sequential = System.nanoTime() - start;
start = System.nanoTime();
long sum2 = large.parallelStream()
.mapToLong(Integer::longValue)
.sum();
long parallel = System.nanoTime() - start;
System.out.println("Sequential: " + sequential);
System.out.println("Parallel: " + parallel);
}
}
Primitive Streams
Specialized streams for primitive types avoid boxing overhead.
IntStream, LongStream, DoubleStream:
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.DoubleStream;
public class PrimitiveStreams {
public static void main(String[] args) {
IntStream.range(1, 5)
.forEach(System.out::println);
IntStream.rangeClosed(1, 5)
.forEach(System.out::println);
int sum = IntStream.of(1, 2, 3, 4, 5).sum();
double avg = IntStream.of(1, 2, 3, 4, 5)
.average()
.orElse(0.0);
int total = List.of(1, 2, 3, 4, 5).stream()
.mapToInt(Integer::intValue)
.sum();
DoubleStream.generate(Math::random)
.limit()
.forEach(System.out::println);
}
}
Real-World Examples
Processing business objects:
class Employee {
private String name;
private String department;
private double salary;
public Employee(String name, String department, double salary) {
this.name = name;
this.department = department;
this.salary = salary;
}
public String getName() { return name; }
public String getDepartment() { return department; }
public double getSalary() { return salary; }
}
public class EmployeeProcessing {
public static void main(String[] args) {
List<Employee> employees = List.of(
new Employee("Alice", "Engineering", 80000),
new Employee("Bob", "Engineering", 90000),
new Employee("Charlie", "Sales", 70000),
(, , )
);
Map<String, Double> avgSalaryByDept = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.averagingDouble(Employee::getSalary)
));
Optional<Employee> highestPaid = employees.stream()
.max((e1, e2) -> Double.compare(e1.getSalary(),
e2.getSalary()));
Map<String, Double> totalByDept = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.summingDouble(Employee::getSalary)
));
List<String> highEarners = employees.stream()
.filter(e -> e.getSalary() > )
.map(Employee::getName)
.collect(Collectors.toList());
}
}
File processing example:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
public class FileProcessing {
public static void main(String[] args) throws IOException {
Files.lines(Paths.get("data.txt"))
.filter(line -> !line.isEmpty())
.map(String::trim)
.forEach(System.out::println);
long wordCount = Files.lines(Paths.get("data.txt"))
.flatMap(line -> Arrays.stream(line.split("\\s+")))
.count();
Set<String> uniqueWords = Files.lines(Paths.get("data.txt"))
.flatMap(line -> Arrays.stream(line.split("\\s+")))
.map(String::toLowerCase)
.collect(Collectors.toSet());
}
}
When to Use This Skill
Use java-streams-api when you need to:
- Process collections with functional-style operations
- Filter, map, or transform data declaratively
- Aggregate or reduce collections to single values
- Group or partition data by criteria
- Chain multiple data transformations
- Process large datasets in parallel
- Write more readable collection processing code
- Avoid explicit loops and mutable state
- Perform lazy evaluation of operations
- Work with infinite sequences efficiently
Best Practices
- Use method references when possible for readability
- Avoid side effects in stream operations
- Close streams from I/O sources (Files.lines, etc.)
- Prefer collect() over forEach() for accumulation
- Use primitive streams to avoid boxing overhead
- Keep stream pipelines readable with proper formatting
- Use parallel streams only for large datasets
- Don't reuse streams - they're one-time use
- Prefer Optional over null checks in results
- Use Collectors factory methods for common operations
Common Pitfalls
- Reusing streams after terminal operation (throws exception)
- Modifying source collection during stream processing
- Using parallel streams for small datasets (overhead cost)
- Side effects in stateless operations (unpredictable results)
- Not handling Optional results properly
- Excessive chaining making code unreadable
- Forgetting to close streams from I/O sources
- Using forEach() when collect() is more appropriate
- Not considering thread safety in parallel streams
- Performance issues from unnecessary boxing/unboxing
Resources