Skip to Content
现代 Java 配方
book

现代 Java 配方

by Ken Kousen
July 2025
Intermediate to advanced
322 pages
3h 52m
Chinese
O'Reilly Media, Inc.
Content preview from 现代 Java 配方

第 2 章 java.util.function 包

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

上一章讨论了 Lambda 表达式和方法引用的基本语法。其中一个基本原则是,无论哪种表达式,都有一个上下文。Lambda 表达式和方法引用总是分配给功能接口,这些接口提供了关于正在实现的单个抽象方法的信息。

虽然 Java 标准库中的许多接口只包含一个抽象方法,因此属于函数式接口,但有一个新的包专门设计用于只包含函数式接口,并在库的其余部分中重复使用。这个包叫做java.util.function

java.util.function 中的接口分为四类:(1) 消费者;(2) 供应商;(3) 谓词;(4) 函数。消费者接收一个通用参数,不返回任何值。Suppliers 不接收任何参数,返回一个值。谓词有一个参数,返回一个布尔值。函数只接受一个参数,并返回一个值。

每个基本接口都有几个相关接口。例如,Consumer 有为原始类型定制的变体(IntConsumerLongConsumerDou⁠bleConsumer ),还有一个变体(BiConsumer ),它接受两个参数并返回void

虽然根据定义,本章中的接口只包含一个抽象方法,但大多数接口还包含staticdefault 的附加方法。熟悉这些方法将使开发人员的工作更加轻松。

2.1 消费者

问题

您想编写实现java.util.function⁠.Consumer 包的 Lambda 表达式。

解决方案

使用 lambda 表达式或方法引用实现void accept(T t) 方法。

讨论

java.util.function.Consumer 接口有一个抽象方法void accept(T t) 。请参见例 2-1

例 2-1. java.util.function.Consumer 中的方法
        void        accept(T t)                        1
default Consumer<T> andThen(Consumer<? super T> after) 2
1

单一抽象方法

2

组成的默认方法

accept 方法接收一个泛型参数并返回void 。最常用的 方法示例之一是java.util.Iterable 中的默认forEach 方法,它以Consumer 为参数,如例 2-2 所示。

例 2-2. Iterable 中的 forEach 方法
default void forEach(Consumer<? super ...
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 烹饪书,第 4 版

Java 烹饪书,第 4 版

Ian F. Darwin
Java Server Pages

Java Server Pages

Hans Bergsten

Publisher Resources

ISBN: 9798341663015