Backend Development 12 min read

Using Java 8 Stream API for Data Processing: Filters, Maps, Sorting, and Parallel Streams

This article introduces Java 8's Stream API, explains its declarative data‑processing style with operations such as filter, map, sorted, forEach, collect, statistics and parallelStream, and provides complete example code demonstrating these concepts on a UserPo class.

Top Architect
Top Architect
Top Architect
Using Java 8 Stream API for Data Processing: Filters, Maps, Sorting, and Parallel Streams

Java 8 added the Stream API, offering a declarative way to process collections similar to SQL queries, where data flows through a pipeline of operations.

The tutorial demonstrates the API using a UserPo class with name and score fields.

filter : selects elements that satisfy a predicate.

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

map : transforms each element into another form.

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

sorted : orders elements, optionally in reverse.

List
filterList = list.stream()
    .filter(p -> null != p.getScore())
    .sorted(Comparator.comparing(UserPo::getScore).reversed())
    .collect(Collectors.toList());

forEach : performs an action on each element, often mutating the original objects.

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

collect : aggregates elements, e.g., grouping by a field.

Map
> groupByScoreMap = list.stream()
    .filter(p -> null != p.getScore())
    .collect(Collectors.groupingBy(UserPo::getScore));

statistics : computes summary statistics such as max, min, sum, and average.

DoubleSummaryStatistics statistics = filterList.stream()
    .mapToDouble(p -> p.getScore())
    .summaryStatistics();

parallelStream : enables parallel processing to improve performance, but requires careful evaluation.

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

Complete example code:

public class UserPo {
    private String name;
    private Double score;
    public UserPo(String name, Double score) { this.name = name; this.score = score; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public Double getScore() { return score; }
    public void setScore(Double score) { this.score = score; }
    @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.0d));
        list.add(new UserPo("小五", 50.0d));
        list.add(new UserPo("小六", 60.0d));
        list.add(new UserPo("小6", 60.0d));
        list.add(new UserPo("小空", null));
        list.add(new UserPo("小九", 90.0d));

        long count = list.stream().filter(p -> p.getScore() != null).count();
        System.out.println("参加考试的学生人数:" + count);

        List
filterList = list.stream()
            .filter(p -> p.getScore() != null)
            .collect(Collectors.toList());
        System.out.println("参加考试的学生信息:");
        filterList.forEach(System.out::println);

        List
scoreList = list.stream().map(UserPo::getScore).collect(Collectors.toList());
        System.out.println("所有学生的成绩集合:" + scoreList);

        String nameString = list.stream().map(UserPo::getName).collect(Collectors.joining(","));
        System.out.println("所有学生的姓名字符串:" + nameString);

        filterList = list.stream()
            .filter(p -> p.getScore() != null)
            .sorted(Comparator.comparing(UserPo::getScore).reversed())
            .collect(Collectors.toList());
        System.out.println("所有学生的成绩集合,逆序排序:");
        filterList.forEach(System.out::println);

        Map
> groupByScoreMap = list.stream()
            .filter(p -> p.getScore() != null)
            .collect(Collectors.groupingBy(UserPo::getScore));
        for (Map.Entry
> entry : groupByScoreMap.entrySet()) {
            System.out.println("成绩:" + entry.getKey() + " 人数:" + entry.getValue().size());
        }

        filterList.forEach(p -> p.setScore(p.getScore() + 10));
        System.out.println("及格人数太少,给每个人加10分");
        filterList.forEach(System.out::println);

        DoubleSummaryStatistics stats = filterList.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 article also includes promotional messages for a ChatGPT community and related services, but the core instructional content remains a practical guide to Java Stream operations.

Javabackend developmentFunctional ProgrammingCode ExampleStream APIJava 8
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.