Skip to Content
Kotlin 编程实践
book

Kotlin 编程实践

by Ken Kousen
July 2020
Intermediate to advanced
235 pages
3h 37m
Chinese
China Machine Press
Content preview from Kotlin 编程实践
序列
115
filtering 202
doubling 102
filtering 204
对于序列,它不会在意你使用了 filter 函数还是重载的 first 函数。后者也许更简
单,但是无论哪种方式,都只进行 6 次计算,因为序列在处理下一个元素之前,每个元
素都已经完全经过了整条流水线的处理。注意,只是为了证明一点,这次的序列上限已
更改为 200 万,但这丝毫不影响最终的行为。
顺便说一句,如果序列为空,则此处使用的第一个函数将抛出异常。如果发生这种情
况,请考虑改为使用 firstOrNull
Sequence API 包含了 Collection 相同的函数,但操作分为两类:
过渡操作
末端操作
。过渡操作(例如 map filter),返回一个新的序列。末端操作(例如
first toList),可能返回任何其他东西。其中的关键在于,没有末端操作,序列
将不会处理任何数据。
仅当在序列上调用的链式函数的流水线以终端操作结束时,序列才开始处理
数据。与 Java 流不同,Kotlin 序列可以被遍历多次,虽然有些时候不行,并
且被记录了下来。
6.2
生成序列
问题
如何生成值的序列?
解决方案
如果你已经拥有了元素,可以使用 sequenceOf 函数,如果你已经拥有了 Iterable
可以使用 asSequence 函数,或使用其他的生成方式。
讨论
前两种情况都很简单,sequenceOf 的工作方式与 arrayOflistOf,或其他相关
的函数相同。asSequence ...
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

GraphQL 学习指南

GraphQL 学习指南

Eve Porcello, Alex Banks
Java 技术手册(原书第7版)

Java 技术手册(原书第7版)

Benjamin J. Evans, David Flanagan
Python机器学习基础教程

Python机器学习基础教程

Andreas C. Müller, Sarah Guido

Publisher Resources

ISBN: 9787111659624