Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Kotlin Collection関数をマスター

Kotlin Collection関数をマスター

Kotlin Fest 2024にて登壇させていただいた資料です。
KotlinのCollection関数を、たくさん紹介させていただきました。

Masayuki Suda

June 22, 2024
Tweet

More Decks by Masayuki Suda

Other Decks in Programming

Transcript

  1. ໨࣍ 01. ΠϯτϩμΫγϣϯ 1.1 ࣗݾ঺հ 1.2 ͖͔͚ͬ 04. ؔ਺ͷ঺հ2 4.1

    ෦෼औಘ 4.2 ୯Ұཁૉऔಘ 05. ߴ౓ͳؔ਺ͷ࢖༻ྫ 5.1 chunked 5.2 windowed 02. Kotlin Collectionͷ֓ཁ 2.1 ϑϨʔϜϫʔΫجຊߏ଄ 2.2 ओཁͳΠϯλʔϑΣʔε 03. ؔ਺ͷ঺հ1 3.1 ม׵ 3.2 ϑΟϧλϦϯά 06. ύϑΥʔϚϯεͷ࠷దԽ 6.1 Sequenceͱforจ 6.2 ·ͱΊ 3.3 ཁૉͷ௥Ճɾ࡟আ 3.4 άϧʔϓԽ 4.3 ฒ΂ସ͑ 4.4 ू໿ؔ਺
  2. 3.1 ม׵ Associateɹ ஫ҙ఺ ɾPair ObjectΛଟ਺ੜ੒ͯ͠͠·͏͜ͱͷݒ೦ ɹɾ֤Collectionཁૉʹରͯ͠୹໋ͷPair ObjectΛੜ੒͠·͢ɻ͜ΕʹΑΓɺҰ࣌తͳϝϞϦ࢖༻ྔ͕૿Ճ͠·͢ɻ ɹɾେن໛ͳCollectionʹରͯ͠associate()Λ࢖༻͢Δͱɺଟ਺ͷPair Object͕࡞੒͞ΕɺΨϕʔδίϨΫγϣϯͷ

    ෛ୲͕૿Ճ͢ΔՄೳੑ͕͋Γ·͢ɻ ɹɾPair ObjectΛੜ੒͢Δίετ͕͔͔Γ·͢ɻ֤ཁૉʹରͯ͠ϖΞΛ࡞੒͢ΔͨΊɺଟ਺ͷObjectੜ੒͕ൃੜ͠ ·͢ɻ ɹɾObjectੜ੒ͷΦʔόʔϔου͕ྦྷੵ͢ΔͱɺύϑΥʔϚϯεʹӨڹΛ༩͑Δ͜ͱ͕͋Γ·͢ɻ ɾύϑΥʔϚϯε͕ॏཁͰͳ͍৔߹΍ɺΩʔͱ஋ΛҰॹʹੜ੒͢Δඞཁ͕͋Δ৔߹ʹద͍ͯ͠·͢ɻ
  3. Flatten 3.1 ม׵ Signature Ex. flatMap() ɾCollectionͷ֤ཁૉʹରͯ͠ࢦఆ͞Εͨม׵ؔ਺Λద༻͠ɺͦͷ݁Ռͱͯ͠ಘΒΕͨCollectionΛ Ұͭʹ·ͱΊͯฏୱԽ͠·͢ɻ ɾܭࢉྔ͸O(n +

    m) ɹɾn͸ݩͷίϨΫγϣϯͷཁૉ਺ɻ ɹɾm͸ม׵͞ΕͨίϨΫγϣϯͷશཁૉ਺ͷ߹ܭɻ ɾΦʔόʔϔου ɹɾ֤ཁૉʹରͯ͠ϦετΛੜ੒͢ΔͨΊɺෆཁͳΦʔόʔϔου͕ൃੜ͢ΔՄೳੑ͕͋Γ·͢ɻ
  4. 3.2 ϑΟϧλϦϯά طଘͷCollectionΛϑΟϧλʔ͠ɺ৽͍͠CollectionΛߏங͠·͢ filter(), filterNot() جຊతͳϑΟϧλϦϯάɻ৚݅ʹ߹க͢Δ͔ɺ͠ͳ͍͔ͰϑΟϧλϦ ϯά͠·͢ɻ filterIndexed() Indexͱ஋ʹج͍ͮͯཁૉΛϑΟϧλϦϯά͠·͢ɻ filterIsInstance(),

    filterNotNull() ಛఆͷܕͷཁૉ ɺnull஋Λߟྀͯ͠ϑΟϧλϦϯά͠·͢ɻ partition() ৚݅ʹ߹க͢Δཁૉͱ͠ͳ͍ཁૉΛ2ͭͷϦετʹ෼͚·͢ɻ any(), none(), all() Collection಺ͷཁૉ͕৚݅ʹ߹க͢Δ͔Ͳ͏͔ΛνΣοΫ͠·͢ɻ filterTo() طଘͷCollectionʹϑΟϧλϦϯά݁ՌΛ௥Ճ͠·͢ɻ
  5. 4.4 ू໿ؔ਺ maxOrNull() CollectionͷཁૉͷதͰ࠷େͷ΋ͷΛฦ͠·͢ minOrNull() CollectionͷཁૉͷதͰ࠷খͷ΋ͷΛฦ͠·͢ sum() CollectionͷཁૉΛ߹ܭ͢ΔͨΊʹ࢖༻͞Ε·͢ average() Collectionͷ਺஋ཁૉͷฏۉΛܭࢉ͢ΔͨΊʹ࢖༻͞Ε·͢

    count() Collectionͷཁૉͷ਺Λ਺͑ΔͨΊʹ࢖༻͞Ε·͢ fold() ॳظ஋ͱྦྷੵૢ࡞Λࢦఆͯ͠ࠨ͔ΒӈʹίϨΫγϣϯΛંΓͨͨΉɻ reduce() ॳظ஋ͳ͠Ͱ࠷ॳͷཁૉΛॳظ஋ͱͯ͠ࠨ͔ΒӈʹίϨΫγϣϯΛॖখ͢ Δɻ
  6. Special Thanks KotlinެࣜϦϑΝϨϯε https://kotlinlang.org/docs/collections-overview.html Effective Kotlin: Prefer Sequence for big

    collections with more than one processing step https://blog.kotlin-academy.com/effective-kotlin-use-sequence-for-bigger-collections-with-more-than-one- processing-step-649a15bb4bf