Using Java 8 Stream API for POJO Collection Processing
This article introduces Java 8 Stream API, demonstrates filtering, mapping, sorting, collecting, and parallel streams with POJO examples, including code snippets, performance tips, and links to related resources, while also containing promotional messages for ChatGPT services.
Java 8 added the Stream API, a high‑level abstraction that lets developers process collections in a declarative, SQL‑like style. A stream treats the source elements as a pipeline where operations such as filter, sort, map, and collect can be applied.
Similar to Linux pipes, the stream concept is familiar to developers who work with command‑line pipelines. The article uses a POJO (UserPo) to illustrate typical data‑processing scenarios that go beyond simple String lists.
Stream Operations Overview
+--------------------+ +------+ +------+ +---+ +-------+
| stream of elements |->|filter|->|sorted|->|map|->|collect|
+--------------------+ +------+ +------+ +---+ +-------+POJO Definition
public class UserPo {
private String name;
private Double score;
// constructors, getters, setters omitted for brevity
}filter : selects elements that satisfy a predicate.
// Count students with a non‑null score
long count = list.stream()
.filter(p -> p.getScore() != null)
.count();map : transforms each element into another form.
// Extract all scores into a List
List
scoreList = list.stream()
.map(UserPo::getScore)
.collect(Collectors.toList());
// Join all names into a comma‑separated string
String nameString = list.stream()
.map(UserPo::getName)
.collect(Collectors.joining(","));sorted : orders elements, optionally in reverse.
// Sort by score descending
List
sortedList = list.stream()
.filter(p -> p.getScore() != null)
.sorted(Comparator.comparing(UserPo::getScore).reversed())
.collect(Collectors.toList());forEach : performs an action on each element (often mutating the original collection).
// Add 10 points to every student's score
sortedList.stream()
.forEach(p -> p.setScore(p.getScore() + 10));collect : aggregates results, e.g., grouping by a field.
// Group students by score
Map
> groupByScore = list.stream()
.filter(p -> p.getScore() != null)
.collect(Collectors.groupingBy(UserPo::getScore));statistics : obtains summary statistics such as min, max, 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 : leverages multiple threads for potentially faster processing, but without thread‑local context propagation.
// Parallel count of students with a non‑null score
long parallelCount = list.parallelStream()
.filter(p -> p.getScore() != null)
.count();The article also provides the complete source code for UserPo and a StreamTest class that demonstrates all the above operations on a sample list of students.
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));
// ... additional test data ...
// Demonstrations of filter, map, sorted, forEach, collect, statistics, parallelStream
}
}In addition to the technical content, the article contains promotional messages encouraging readers to join a ChatGPT‑related community, purchase services, and download supplemental materials.
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.
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.