Java 8 Stream API Tutorial with POJO Examples
This article introduces Java 8's Stream API, explains its declarative data‑processing style, and demonstrates common operations such as filter, map, sorted, forEach, collect, statistics, and parallelStream using a UserPo class with full runnable code examples.
Java 8 added a new abstraction called Stream, allowing data to be processed in a declarative, SQL‑like manner; streams treat collections as pipelines where operations like filter, sort, and map can be chained.
The tutorial defines a simple POJO
public class UserPo { private String name; private Double score; /* constructors, getters, setters */ }to illustrate real‑world usage instead of plain strings.
filter : Demonstrates counting students whose score is not null with
long count = list.stream().filter(p -> p.getScore() != null).count();.
map : Shows extracting a list of scores and joining names into a comma‑separated string using
list.stream().map(UserPo::getScore).collect(Collectors.toList());and
list.stream().map(UserPo::getName).collect(Collectors.joining(","));.
sorted : Sorts the filtered list by score in descending order via
list.stream().filter(p -> p.getScore() != null).sorted(Comparator.comparing(UserPo::getScore).reversed()).collect(Collectors.toList());.
forEach : Applies a custom action to each element, e.g., adding 10 points to every student's score with
filterList.stream().forEach(p -> p.setScore(p.getScore() + 10));. A note warns that only forEach mutates the original collection.
collect : Uses Collectors.groupingBy to group students by score, returns a list of scores, or joins names into a string, illustrating various collection results.
statistics : Computes summary statistics (max, min, sum, average) on scores via
DoubleSummaryStatistics stats = filterList.stream().mapToDouble(UserPo::getScore).summaryStatistics();.
parallelStream : Shows parallel processing with
long parallelCount = list.parallelStream().filter(p -> p.getScore() != null).count();, noting the need for careful evaluation of thread‑safety.
The article concludes with the complete source code for UserPo and a StreamTest class containing imports, data setup, and all demonstrated stream operations inside the main method.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
