<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # 集合轉換 [TOC] Kotlin 標準庫為集合 _轉換_ 提供了一組擴展函數。這些函數根據提供的轉換規則從現有集合中構建新集合。在此頁面中,我們將概述可用的集合轉換函數。 ## 映射 _映射_ 轉換從另一個集合的元素上的函數結果創建一個集合。基本的映射函數是 [`map()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map.html)。它將給定的 lambda 函數應用于每個后續元素,并返回 lambda 結果列表。結果的順序與元素的原始順序相同。如需應用還要用到元素索引作為參數的轉換,請使用 [`mapIndexed()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map-indexed.html)。 ```kotlin fun main() { //sampleStart val numbers = setOf(1, 2, 3) println(numbers.map { it * 3 }) println(numbers.mapIndexed { idx, value -> value * idx }) //sampleEnd } ``` 如果轉換在某些元素上產生 `null` 值,則可以通過調用 [`mapNotNull()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map-not-null.html) 函數取代 `map()` 或 [`mapIndexedNotNull()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map-indexed-not-null.html) 取代 `mapIndexed()` 來從結果集中過濾掉 `null` 值。 ```kotlin fun main() { //sampleStart val numbers = setOf(1, 2, 3) println(numbers.mapNotNull { if ( it == 2) null else it * 3 }) println(numbers.mapIndexedNotNull { idx, value -> if (idx == 0) null else value * idx }) //sampleEnd } ``` 映射轉換時,有兩個選擇:轉換鍵,使值保持不變,反之亦然。要將指定轉換應用于鍵,請使用 [`mapKeys()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map-keys.html);反過來,[`mapValues()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map-values.html) 轉換值。這兩個函數都使用將映射條目作為參數的轉換,因此可以操作其鍵與值。 ```kotlin fun main() { //sampleStart val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11) println(numbersMap.mapKeys { it.key.toUpperCase() }) println(numbersMap.mapValues { it.value + it.key.length }) //sampleEnd } ``` ## 雙路合并 _雙路合并_ 轉換是根據兩個集合中具有相同位置的元素構建配對。在 Kotlin 標準庫中,這是通過 [`zip()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/zip.html) 擴展函數完成的。在一個集合(或數組)上以另一個集合(或數組)作為參數調用時,`zip()` 返回 `Pair` 對象的列表(`List`)。接收者集合的元素是這些配對中的第一個元素。如果集合的大小不同,則 `zip()` 的結果為較小集合的大小;結果中不包含較大集合的后續元素。`zip()` 也可以中綴形式調用 `a zip b` 。 ```kotlin fun main() { //sampleStart val colors = listOf("red", "brown", "grey") val animals = listOf("fox", "bear", "wolf") println(colors zip animals) val twoAnimals = listOf("fox", "bear") println(colors.zip(twoAnimals)) //sampleEnd } ``` 也可以使用帶有兩個參數的轉換函數來調用 `zip()`:接收者元素和參數元素。在這種情況下,結果 `List` 包含在具有相同位置的接收者對和參數元素對上調用的轉換函數的返回值。 ```kotlin fun main() { //sampleStart val colors = listOf("red", "brown", "grey") val animals = listOf("fox", "bear", "wolf") println(colors.zip(animals) { color, animal -> "The ${animal.capitalize()} is $color"}) //sampleEnd } ``` 當擁有 `Pair` 的 `List` 時,可以進行反向轉換 _unzipping_——從這些鍵值對中構建兩個列表: * 第一個列表包含原始列表中每個 `Pair` 的鍵。 * 第二個列表包含原始列表中每個 `Pair` 的值。 要分割鍵值對列表,請調用 [`unzip()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/unzip.html)。 ```kotlin fun main() { //sampleStart val numberPairs = listOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) println(numberPairs.unzip()) //sampleEnd } ``` ## 關聯 _關聯_ 轉換允許從集合元素和與其關聯的某些值構建 Map。在不同的關聯類型中,元素可以是關聯 Map 中的鍵或值。 基本的關聯函數 [`associateWith()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/associate-with.html) 創建一個 `Map`,其中原始集合的元素是鍵,并通過給定的轉換函數從中產生值。如果兩個元素相等,則僅最后一個保留在 Map 中。 ```kotlin fun main() { //sampleStart val numbers = listOf("one", "two", "three", "four") println(numbers.associateWith { it.length }) //sampleEnd } ``` 為了使用集合元素作為值來構建 Map,有一個函數 [`associateBy()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/associate-by.html)。它需要一個函數,該函數根據元素的值返回鍵。如果兩個元素相等,則僅最后一個保留在 Map 中。還可以使用值轉換函數來調用 `associateBy()`。 ```kotlin fun main() { //sampleStart val numbers = listOf("one", "two", "three", "four") println(numbers.associateBy { it.first().toUpperCase() }) println(numbers.associateBy(keySelector = { it.first().toUpperCase() }, valueTransform = { it.length })) //sampleEnd } ``` 另一種構建 Map 的方法是使用函數 [`associate()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/associate.html),其中 Map 鍵和值都是通過集合元素生成的。它需要一個 lambda 函數,該函數返回 `Pair`:鍵和相應 Map 條目的值。 請注意,`associate()` 會生成臨時的 `Pair` 對象,這可能會影響性能。因此,當性能不是很關鍵或比其他選項更可取時,應使用 `associate()`。 后者的一個示例:從一個元素一起生成鍵和相應的值。 ```kotlin fun main() { data class FullName (val firstName: String, val lastName: String) fun parseFullName(fullName: String): FullName { val nameParts = fullName.split(" ") if (nameParts.size == 2) { return FullName(nameParts[0], nameParts[1]) } else throw Exception("Wrong name format") } //sampleStart val names = listOf("Alice Adams", "Brian Brown", "Clara Campbell") println(names.associate { name -> parseFullName(name).let { it.lastName to it.firstName } }) //sampleEnd } ``` 此時,首先在一個元素上調用一個轉換函數,然后根據該函數結果的屬性建立 Pair。 ## 打平 如需操作嵌套的集合,則可能會發現提供對嵌套集合元素進行打平訪問的標準庫函數很有用。 第一個函數為 [`flatten()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/flatten.html)。可以在一個集合的集合(例如,一個 `Set` 組成的 `List`)上調用它。該函數返回嵌套集合中的所有元素的一個 `List`。 ```kotlin fun main() { //sampleStart val numberSets = listOf(setOf(1, 2, 3), setOf(4, 5, 6), setOf(1, 2)) println(numberSets.flatten()) //sampleEnd } ``` 另一個函數——[`flatMap()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/flat-map.html) 提供了一種靈活的方式來處理嵌套的集合。它需要一個函數將一個集合元素映射到另一個集合。因此,`flatMap()` 返回單個列表其中包含所有元素的值。所以,`flatMap()` 表現為 `map()`(以集合作為映射結果)與 `flatten()` 的連續調用。 ```kotlin data class StringContainer(val values: List<String>) fun main() { //sampleStart val containers = listOf( StringContainer(listOf("one", "two", "three")), StringContainer(listOf("four", "five", "six")), StringContainer(listOf("seven", "eight")) ) println(containers.flatMap { it.values }) //sampleEnd } ``` ## 字符串表示 如果需要以可讀格式檢索集合內容,請使用將集合轉換為字符串的函數:[`joinToString()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/join-to-string.html) 與 [`joinTo()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/join-to.html)。 `joinToString()` 根據提供的參數從集合元素構建單個 `String`。`joinTo()` 執行相同的操作,但將結果附加到給定的 [`Appendable`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/-appendable/index.html) 對象。 當使用默認參數調用時,函數返回的結果類似于在集合上調用 `toString()`:各元素的字符串表示形式以空格分隔而成的 `String`。 ```kotlin fun main() { //sampleStart val numbers = listOf("one", "two", "three", "four") println(numbers) println(numbers.joinToString()) val listString = StringBuffer("The list of numbers: ") numbers.joinTo(listString) println(listString) //sampleEnd } ``` 要構建自定義字符串表示形式,可以在函數參數 `separator`、`prefix` 與 `postfix`中指定其參數。 結果字符串將以 `prefix` 開頭,以 `postfix` 結尾。除最后一個元素外,`separator` 將位于每個元素之后。 ```kotlin fun main() { //sampleStart val numbers = listOf("one", "two", "three", "four") println(numbers.joinToString(separator = " | ", prefix = "start: ", postfix = ": end")) //sampleEnd } ``` 對于較大的集合,可能需要指定 `limit` ——將包含在結果中元素的數量。如果集合大小超出 `limit`,所有其他元素將被 `truncated` 參數的單個值替換。 ```kotlin fun main() { //sampleStart val numbers = (1..100).toList() println(numbers.joinToString(limit = 10, truncated = "<...>")) //sampleEnd } ``` 最后,要自定義元素本身的表示形式,請提供 `transform` 函數。 ```kotlin fun main() { //sampleStart val numbers = listOf("one", "two", "three", "four") println(numbers.joinToString { "Element: ${it.toUpperCase()}"}) //sampleEnd } ```
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看