Skip to Content
Java 的函数式方法
book

Java 的函数式方法

by Ben Weidig
May 2025
Intermediate to advanced
414 pages
4h 48m
Chinese
O'Reilly Media, Inc.
Content preview from Java 的函数式方法

第 6 章 数据流的数据处理 使用数据流处理数据

本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com

几乎所有程序都要处理数据,而且很可能是以集合(Collections)的形式处理数据。 命令式方法使用循环来遍历元素,依次处理每个元素。 不过,函数式语言更喜欢声明式方法,有时甚至从一开始就没有经典的循环语句。

Java 8 中引入的Streams API 提供了一种完全声明式和懒散评估式的数据处理方法,通过利用高阶函数进行大部分操作,该方法从 Java 的函数式添加中获益匪浅。

本章将向你介绍命令式数据处理和声明式数据处理之间的区别,然后将对 Streams 进行直观介绍,突出其基本概念,并向你展示如何最大限度地利用其灵活性来实现功能更强的数据处理方法。

迭代数据处理

处理数据是一项日常工作,您可能已经遇到过无数次,而且今后还会继续遇到。

从广义上讲,任何类型的数据处理都像一个流水线,由一个数据结构(如集合)提供元素,然后进行一个或多个操作(如过滤或转换元素),最后产生某种形式的结果。 结果可能是另一个数据结构,甚至可能用来运行另一个任务。

让我们从一个简单的数据处理示例开始。

外部迭代

假设我们需要从Book 实例列表中按标题排序找到 1970 年以前的三本科幻小说。例 6-1展示了如何使用典型的命令式方法和for 循环来实现这一目标。

例 6-1. 使用for 循环查找图书
record Book(String title, int year, Genre genre) {
  // NO BODY
}

// DATA PREPARATION

List<Book> books = ...; 1

Collections.sort(books, Comparator.comparing(Book::title)); 2

// FOR-LOOP

List<String> result = new ArrayList<>();

for (var book : books) {
    if (book.year() >= 1970) { 3
        continue;
    }

    if (book.genre() != Genre.SCIENCE_FICTION) { 3
        continue;
    }

    var title = book.title(); 
    result.add(title);

    if (result.size() == 3) { 
        break;
    }
}

一个未排序的书籍集合,必须是可变的,以便下一步就地排序。 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Java Server Pages

Java Server Pages

Hans Bergsten

Publisher Resources

ISBN: 9798341658073