构造对比:
1.集合
这里setOf和mutableSetOf就是一个只读,一个支持修改处理。因为集合泛型的擦除,val和var其实不能控制只读和读写。故用这种构造方法。
// 挨个元素传入
val numbersSet = setOf("one", "two", "three", "four")
val emptySet = mutableSetOf<String>()
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)
// 函数方式,或者集合方式
val numbersMap = mutableMapOf<String, String>().apply { this["one"] = "1"; this["two"] = "2" }
val sourceList = mutableListOf(1, 2, 3)
val copyList = sourceList.toMutableList()
val readOnlyCopyList = sourceList.toList()
sourceList.add(4)
2.序列
// 挨个传入
val numbersSequence = sequenceOf("four", "three", "two", "one")
// 集合转换过去
val numbers = listOf("one", "two", "three", "four")
val numbersSequence = numbers.asSequence()
// 函数转换
val oddNumbers = generateSequence(1) { it + 2 } // `it` 是上一个元素
println(oddNumbers.take(5).toList())
当然,构造方法不止这些,这里也只是粗略对比。
处理元素:
集合
假定有一个单词列表。下面的代码过滤长于三个字符的单词,并打印前四个单词的长度。
val words = "The quick brown fox jumps over the lazy dog".split(" ")
val lengthsList = words.filter { println("filter: $it"); it.length > 3 }
.map { println("length: ${it.length}"); it.length }
.take(4)
println("Lengths of first 4 words longer than 3 chars:")
println(lengthsList)
filter: The
filter: quick
filter: brown
filter: fox
filter: jumps
filter: over
filter: the
filter: lazy
filter: dog
length: 5
length: 5
length: 5
length: 4
length: 4
Lengths of first 4 words longer than 3 chars:
[5, 5, 5, 4]
运行此代码时,会看到?filter() ?与?map() ?函数的执行顺序与代码中出现的顺序相同。 首先,将看到?filter :对于所有元素,然后是?length :对于在过滤之后剩余的元素,然后是最后两行的输出。 列表处理如下图:
?序列
现在用序列写相同的逻辑:
val words = "The quick brown fox jumps over the lazy dog".split(" ")
// 将列表转换为序列
val wordsSequence = words.asSequence()
val lengthsSequence = wordsSequence.filter { println("filter: $it"); it.length > 3 }
.map { println("length: ${it.length}"); it.length }
.take(4)
println("Lengths of first 4 words longer than 3 chars")
// 末端操作:以列表形式获取结果。
println(lengthsSequence.toList())
Lengths of first 4 words longer than 3 chars
filter: The
filter: quick
length: 5
filter: brown
length: 5
filter: fox
filter: jumps
length: 5
filter: over
length: 4
[5, 5, 5, 4]
此代码的输出表明,仅在构建结果列表时才调用?filter() ?与?map() ?函数。 因此,首先看到文本?“Lengths of..” ?的行,然后开始进行序列处理。 请注意,对于过滤后剩余的元素,映射在过滤下一个元素之前执行。 当结果大小达到 4 时,处理将停止,因为它是?take(4) ?可以返回的最大大小。
序列处理如下图:
|