Backend Development 13 min read

Java 8 Stream API: Practical Guide for PO Processing with Filter, Map, Sorted, Collect, and ParallelStream

This article introduces Java 8 Stream API, explains its functional style similar to SQL, and demonstrates how to process PO objects using filter, map, sorted, forEach, collect, statistics, and parallelStream operations with complete code examples.

Top Architect
Top Architect
Top Architect
Java 8 Stream API: Practical Guide for PO Processing with Filter, Map, Sorted, Collect, and ParallelStream

Java 8 added the Stream API, a high‑level abstraction that lets developers process collections in a declarative, SQL‑like manner, treating the data as a flow through a pipeline of operations.

The style is analogous to Linux pipelines and is especially useful when handling PO/VO objects rather than simple strings.

Stream Pipeline Overview

+--------------------+ +------+ +------+ +---+ +-------+
| stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|
+--------------------+ +------+ +------+ +---+ +-------+

Filter

Filters elements based on a predicate; only those matching the condition pass through.

// Count students whose score is not null
long count = list.stream().filter(p -> p.getScore() != null).count();

Map

Transforms each element into another form, e.g., extracting a list of scores or concatenating names.

// Extract all scores
List
scoreList = list.stream().map(p -> p.getScore()).collect(Collectors.toList());
// Join all names with commas
String nameString = list.stream().map(p -> p.getName()).collect(Collectors.joining(","));

Sorted

Orders the stream; the example sorts by score in descending order.

// Sort by score descending
List
sortedList = list.stream()
.filter(p -> p.getScore() != null)
.sorted(Comparator.comparing(UserPo::getScore).reversed())
.collect(Collectors.toList());

forEach

Applies an action to each element; here it adds 10 points to every student's score.

// Add 10 points to each student
sortedList.stream().forEach(p -> p.setScore(p.getScore() + 10));
Note: Only operations like map, filter, sorted do not modify the original collection; forEach can change the elements.

Collect

Aggregates results, useful for grouping, converting to lists, or joining strings.

// Group by score
Map
> groupByScore = list.stream()
.filter(p -> p.getScore() != null)
.collect(Collectors.groupingBy(UserPo::getScore));
// Convert to list
List
scores = list.stream().map(UserPo::getScore).collect(Collectors.toList());

Statistics

Provides summary statistics such as max, min, sum, and average.

DoubleSummaryStatistics stats = filteredList.stream()
.mapToDouble(UserPo::getScore)
.summaryStatistics();
System.out.println("Max: " + stats.getMax());
System.out.println("Min: " + stats.getMin());
System.out.println("Sum: " + stats.getSum());
System.out.println("Avg: " + stats.getAverage());

ParallelStream

Enables parallel processing of streams to leverage multiple CPU cores, but requires careful evaluation of thread‑safety.

// Parallel count of students with a score
long parallelCount = list.parallelStream()
.filter(p -> p.getScore() != null)
.count();

Complete Example Code

public class UserPo {
private String name;
private Double score;
// Constructors, getters, setters omitted for brevity
@Override
public String toString() {
return "UserPo{" + "name='" + name + '\'' + ", score=" + score + '}';
}
}
public class StreamTest {
public static void main(String[] args) {
List
list = new ArrayList<>();
list.add(new UserPo("小一", 10.0));
list.add(new UserPo("小五", 50.0));
list.add(new UserPo("小六", 60.0));
list.add(new UserPo("小6", 60.0));
list.add(new UserPo("小空", null));
list.add(new UserPo("小九", 90.0));
long count = list.stream().filter(p -> p.getScore() != null).count();
System.out.println("参加考试的学生人数:" + count);
List
filtered = list.stream()
.filter(p -> p.getScore() != null)
.collect(Collectors.toList());
System.out.println("参加考试的学生信息:");
filtered.forEach(System.out::println);
List
scores = list.stream().map(UserPo::getScore).collect(Collectors.toList());
System.out.println("所有学生的成绩集合:" + scores);
String names = list.stream().map(UserPo::getName).collect(Collectors.joining(","));
System.out.println("所有学生的姓名字符串:" + names);
List
sorted = list.stream()
.filter(p -> p.getScore() != null)
.sorted(Comparator.comparing(UserPo::getScore).reversed())
.collect(Collectors.toList());
System.out.println("所有学生的成绩集合,逆序排序:");
sorted.forEach(System.out::println);
Map
> groupByScore = list.stream()
.filter(p -> p.getScore() != null)
.collect(Collectors.groupingBy(UserPo::getScore));
groupByScore.forEach((score, users) ->
System.out.println("成绩:" + score + " 人数:" + users.size()));
sorted.forEach(p -> p.setScore(p.getScore() + 10));
System.out.println("及格人数太少,给每个人加10分");
sorted.forEach(System.out::println);
long passCount = sorted.stream().filter(p -> p.getScore() >= 60).count();
System.out.println("最后及格人数" + passCount);
DoubleSummaryStatistics stats = sorted.stream()
.mapToDouble(UserPo::getScore)
.summaryStatistics();
System.out.println("列表中最大的数 : " + stats.getMax());
System.out.println("列表中最小的数 : " + stats.getMin());
System.out.println("所有数之和 : " + stats.getSum());
System.out.println("平均数 : " + stats.getAverage());
long parallelCount = list.parallelStream()
.filter(p -> p.getScore() != null)
.count();
System.out.println("并行流处理参加考试的学生人数:" + parallelCount);
}
}

The tutorial demonstrates how to replace verbose for‑loops with concise Stream operations, improving readability and maintainability when processing collections of PO objects.

BackendJavaFunctional ProgrammingCollectionsStream APILambda Expressions
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.