javabeginner
Java Streams — Filter, Map, Collect
Process collections with Java Streams: filter, map, flatMap, reduce, and collect to lists or maps.
javaPress ⌘/Ctrl + Shift + C to copy
import java.util.*;
import java.util.stream.*;
public class StreamBasics {
record Person(String name, int age, String city) {}
public static void main(String[] args) {
List<Person> people = List.of(
new Person("Alice", 30, "NYC"),
new Person("Bob", 25, "LA"),
new Person("Charlie", 35, "NYC"),
new Person("Diana", 28, "LA")
);
// Filter + Map + Collect
List<String> nycNames = people.stream()
.filter(p -> p.city().equals("NYC"))
.map(Person::name)
.sorted()
.collect(Collectors.toList());
System.out.println(nycNames); // [Alice, Charlie]
// Average age
double avgAge = people.stream()
.mapToInt(Person::age)
.average()
.orElse(0.0);
System.out.printf("Average age: %.1f%n", avgAge);
// Group by city
Map<String, List<Person>> byCity = people.stream()
.collect(Collectors.groupingBy(Person::city));
// Count per city
Map<String, Long> countByCity = people.stream()
.collect(Collectors.groupingBy(Person::city, Collectors.counting()));
// Partition: age >= 30 vs < 30
Map<Boolean, List<Person>> partitioned = people.stream()
.collect(Collectors.partitioningBy(p -> p.age() >= 30));
// Join names
String names = people.stream()
.map(Person::name)
.collect(Collectors.joining(", "));
System.out.println(names); // Alice, Bob, Charlie, Diana
}
}Use Cases
- Transforming and filtering collections
- Aggregating data with grouping and partitioning
- Replacing verbose loops with declarative pipelines
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
javaadvanced
Advanced Streams — Custom Collectors
Advanced Stream operations: custom collectors, flatMap, reduce, teeing, and parallel streams.
Best for: Complex data aggregation and reporting
#java#streams
javaintermediate
Stream MapReduce and Aggregation
Use streams for MapReduce-style operations: reduce, collect, summarize, and complex aggregations.
Best for: Sales data aggregation and reporting
#java#streams
javabeginner
Read File Line by Line in Java
Read files using BufferedReader, Files.readAllLines, and Stream API with proper resource management.
Best for: Processing log files line by line
#java#file-io
javabeginner
HashMap Operations and Patterns
Essential HashMap operations: put, get, merge, compute, getOrDefault, and iteration patterns.
Best for: Counting word frequencies in text
#java#collections