Kotlin Collections APIの概要
1. 概要
このクイックチュートリアルでは、KotlinのCollections APIを紹介し、Kotlinのさまざまなコレクションタイプとコレクションの一般的な操作について説明します。
2. コレクションvs 可変コレクション
まず、Kotlinのさまざまな種類のコレクションを見てみましょう。 コレクションの基本タイプを初期化する方法を確認します。
Collectionインターフェースは読み取り専用メソッドをサポートし、MutableCollectionは読み取り/書き込みメソッドをサポートします。
2.1. List
メソッドlistOf()を使用して単純な読み取り専用Listを作成し、mutableListOf()を使用して読み取り/書き込みMutableListを作成できます。
val theList = listOf("one", "two", "three")
val theMutableList = mutableListOf("one", "two", "three")
2.2. Set
同様に、メソッドsetOf()を使用して読み取り専用Setを作成し、mutableSetOf()を使用して読み取り/書き込みMutableSetを作成できます。
val theSet = setOf("one", "two", "three")
val theMutableSet = mutableSetOf("one", "two", "three")
2.3. Map
メソッドmapOf()を使用して読み取り専用Mapを作成し、mutableMapOf()を使用して読み取り/書き込みMutableMapを作成することもできます。
val theMap = mapOf(1 to "one", 2 to "two", 3 to "three")
val theMutableMap = mutableMapOf(1 to "one", 2 to "two", 3 to "three")
3. 便利な演算子
KotlinのCollectionsAPIは、Javaで見つけることができるものよりもはるかに豊富で、オーバーロードされた演算子のセットが付属しています。
3.1. 「in”演算子
collection.contains(x)に変換できる式「x in collection」を使用できます。
@Test
fun whenSearchForExistingItem_thenFound () {
val theList = listOf("one", "two", "three")
assertTrue("two" in theList)
}
3.2. “+”演算子
“â€演算子を使用して、要素またはコレクション全体を別のものにできます。
@Test
fun whenJoinTwoCollections_thenSuccess () {
val firstList = listOf("one", "two", "three")
val secondList = listOf("four", "five", "six")
val resultList = firstList + secondList
assertEquals(6, resultList.size)
assertTrue(resultList.contains("two"))
assertTrue(resultList.contains("five"))
}
3.3. “-“演算子
同様に、「-」演算子を使用して1つまたは複数の要素を削除できます。
@Test
fun whenExcludeItems_thenRemoved () {
val firstList = listOf("one", "two", "three")
val secondList = listOf("one", "three")
val resultList = firstList - secondList
assertEquals(1, resultList.size)
assertTrue(resultList.contains("two"))
}
4. その他の方法
最後に、コレクションの一般的な方法をいくつか検討します。 Javaでは、高度なメソッドを活用する場合は、StreamAPIを使用する必要があります。
Kotlinでは、Collections APIで利用可能な同様のメソッドを見つけることができます。
与えられたList:からサブリストを取得できます
@Test
fun whenSliceCollection_thenSuccess () {
val theList = listOf("one", "two", "three")
val resultList = theList.slice(1..2)
assertEquals(2, resultList.size)
assertTrue(resultList.contains("two"))
}
List:からすべてのnullを簡単に削除できます
@Test
fun whenFilterNullValues_thenSuccess () {
val theList = listOf("one", null, "two", null, "three")
val resultList = theList.filterNotNull()
assertEquals(3, resultList.size)
}
JavaStream APIのfilter()メソッドと同様に機能するfilter(),を使用して、コレクションアイテムを簡単にフィルタリングできます。
@Test
fun whenFilterNonPositiveValues_thenSuccess () {
val theList = listOf(1, 2, -3, -4, 5, -6)
val resultList = theList.filter{ it > 0}
assertEquals(3, resultList.size)
assertTrue(resultList.contains(1))
assertFalse(resultList.contains(-4))
}
最初のN個のアイテムをドロップできます。
@Test
fun whenDropFirstItems_thenRemoved () {
val theList = listOf("one", "two", "three", "four")
val resultList = theList.drop(2)
assertEquals(2, resultList.size)
assertFalse(resultList.contains("one"))
assertFalse(resultList.contains("two"))
}
与えられた条件を満たす場合、最初のいくつかのアイテムをドロップできます。
@Test
fun whenDropFirstItemsBasedOnCondition_thenRemoved () {
val theList = listOf("one", "two", "three", "four")
val resultList = theList.dropWhile{ it.length < 4 }
assertEquals(2, resultList.size)
assertFalse(resultList.contains("one"))
assertFalse(resultList.contains("two"))
}
要素をグループ化できます。
@Test
fun whenGroupItems_thenSuccess () {
val theList = listOf(1, 2, 3, 4, 5, 6)
val resultMap = theList.groupBy{ it % 3}
assertEquals(3, resultMap.size)
assertTrue(resultMap[1]!!.contains(1))
assertTrue(resultMap[2]!!.contains(5))
}
提供されている関数を使用して、すべての要素をマップできます。
@Test
fun whenApplyFunctionToAllItems_thenSuccess () {
val theList = listOf(1, 2, 3, 4, 5, 6)
val resultList = theList.map{ it * it }
assertEquals(4, resultList[1])
assertEquals(9, resultList[2])
}
flatmap()を使用して、ネストされたコレクションをフラット化できます。 ここでは、StringsをList<String>に変換し、List<List<String>>で終わることを回避しています。
@Test
fun whenApplyMultiOutputFunctionToAllItems_thenSuccess () {
val theList = listOf("John", "Tom")
val resultList = theList.flatMap{ it.toLowerCase().toList() }
assertEquals(7, resultList.size)
}
fold/reduce操作を実行できます。
@Test
fun whenApplyFunctionToAllItemsWithStartingValue_thenSuccess () {
val theList = listOf(1, 2, 3, 4, 5, 6)
val finalResult = theList.fold(0, {acc, i -> acc + (i * i)})
assertEquals(91, finalResult)
}
5. 結論
KotlinのCollectionsAPIといくつかの最も興味深い方法を検討しました。
そして、いつものように、完全なソースコードはover on GitHub.で見つけることができます