Skip to Content
Java 到 Kotlin
book

Java 到 Kotlin

by Duncan McGregor, Nat Pryce
May 2025
Intermediate to advanced
424 pages
6h 12m
Chinese
O'Reilly Media, Inc.
Content preview from Java 到 Kotlin

第 13 章 从流到迭代表再到序列

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

Java 和 Kotlin 都允许我们对集合进行转换和还原。 不过它们的设计目标和实现方式各不相同。 Kotlin 用什么来代替 Java 流,我们应该在什么时候转换,以及如何转换?

Java 流

Java 8 在 2014 年引入了流,很好地利用了新的 Lambda。 假设我们想计算出一些字符串的平均长度,只是空白字符串(只有空白字符的字符串)应被当作空字符串来处理。 以前我们可能会这样写:

public static double averageNonBlankLength(List<String> strings) {
    var sum = 0;
    for (var s : strings) {
        if (!s.isBlank())
            sum += s.length();
    }
    return sum / (double) strings.size();
}

有了 Java 流,我们可以通过先将List 转换为Stream 并应用变换,将此算法表达为filter,map, 和reduce

public static double averageNonBlankLength(List<String> strings) {
    return strings
        .stream()
        .filter(s -> !s.isBlank())
        .mapToInt(String::length)
        .sum()
        / (double) strings.size();
}

我们不必在脑海中运行 for 循环来查看这段代码在做什么,而是可以看到逐行声明的算法步骤,并依靠运行时为我们实现这些步骤。

如果我们真的急于得到这些结果,我们甚至可以写作:

public static double averageNonBlankLength(List<String> strings) {
    return strings
        .parallelStream() 1
        .filter(s -> !s.isBlank())
        .mapToInt(String::length)
        .sum()
        / (double) strings.size();
}
1

parallelStream 会将工作分给多个线程。

这里有不同类型的基本操作:map 更改项的类型,而不是它们的数量;filter 根据某些属性保留或拒绝项,但保持它们的类型不变;sum 是将集合还原为单一属性。本例中未显示的操作是skip(n)limit(n) 。这些操作分别返回不含第一个和最后一个n 元素的数据流。

Java 流是懒惰的:strings.filter(...).mapToInt(...) 除了为某些终端操作(本例中为sum )设置管道以吸入值外,什么也不做。懒惰意味着后面的管道阶段可以限制前面阶段必须执行的工作量。 考虑翻译单词列表,直到我们看到单词STOP 。循环版本可能是这样的: ...

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

使用 Kotlin 进行 Android 编程

使用 Kotlin 进行 Android 编程

Pierre-Olivier Laurence, Amanda Hinchman-Dominguez, G. Blake Meike, Mike Dunn
Programming with MicroPython

Programming with MicroPython

Nicholas H. Tollervey

Publisher Resources

ISBN: 9798341659209