Using Java 8 Stream API for Data Processing with PO Objects

This article introduces Java 8's Stream API, explains its SQL‑like pipeline operations such as filter, map, sorted, forEach, collect, statistics and parallelStream, and demonstrates their usage on a UserPo class with comprehensive code examples for backend developers.

Top Architect
Top Architect
Top Architect
Using Java 8 Stream API for Data Processing with PO Objects

Java 8 added the Stream API, providing a declarative way to process collections similar to SQL queries. It treats a collection as a flow of elements that can be filtered, sorted, mapped, and aggregated through a pipeline of operations.

The article uses a UserPo class with name and score fields to illustrate each Stream operation.

PO Code

public class UserPo {
    private String name;
    private Double score;
    // constructors, getters, setters omitted for brevity
}

filter

Filters elements that satisfy a predicate; for example, counting students whose score is not null.

long count = list.stream()
    .filter(p -> null != p.getScore())
    .count();

map

Transforms each element to another form, such as extracting all scores or joining all names.

List<Double> scoreList = list.stream()
    .map(p -> p.getScore())
    .collect(Collectors.toList());

String nameString = list.stream()
    .map(p -> p.getName())
    .collect(Collectors.joining(","));

sorted

Sorts the stream; the example sorts students by score in descending order.

List<UserPo> sortedList = list.stream()
    .filter(p -> null != p.getScore())
    .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.

sortedList.stream()
    .forEach(p -> p.setScore(p.getScore() + 10));

collect

Aggregates elements, e.g., grouping students by score.

Map<Double, List<UserPo>> groupByScore = list.stream()
    .filter(p -> null != p.getScore())
    .collect(Collectors.groupingBy(UserPo::getScore));

statistics

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

DoubleSummaryStatistics stats = filteredList.stream()
    .mapToDouble(p -> p.getScore())
    .summaryStatistics();

parallelStream

Uses multiple threads to process the stream for better performance, with the same filter example.

long parallelCount = list.parallelStream()
    .filter(p -> null != p.getScore())
    .count();

Full Example

The complete runnable example combines all the above operations, demonstrating how to create a list of UserPo objects, apply filters, mappings, sorting, grouping, statistics, and parallel processing.

package com.cmx.tcn.stream;

import java.util.*;
import java.util.stream.Collectors;

public class StreamTest {
    public static void main(String[] args) {
        List<UserPo> list = new ArrayList<>();
        list.add(new UserPo("小一", 10d));
        list.add(new UserPo("小五", 50d));
        // ... more data ...
        long count = list.stream().filter(p -> null != p.getScore()).count();
        System.out.println("参加考试的学生人数:" + count);
        // other operations as described above
    }
}

The article concludes with a reminder that most Stream operations (except forEach when it mutates data) do not modify the original collection.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javafunctional programmingjava8Stream API
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

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.