Visão geral da API Kotlin Collections

Visão geral da API Kotlin Collections

1. Visão geral

Neste tutorial rápido, apresentaremos a API de coleções do Kotlin e discutiremos os diferentes tipos de coleção em Kotlin e algumas operações comuns em coleções.

2. Coleção vs. Coleção Mutável

Primeiro, vamos dar uma olhada nos diferentes tipos de coleções em Kotlin. Vamos ver como inicializar tipos básicos de coleções.

A interfaceCollection oferece suporte a métodos somente leitura, enquantoMutableCollection oferece suporte a métodos de leitura / gravação.

2.1. List

Podemos criar umList simples somente leitura usando o métodolistOf()e leitura-gravaçãoMutableList usandomutableListOf():

val theList = listOf("one", "two", "three")

val theMutableList = mutableListOf("one", "two", "three")

2.2. Set

Da mesma forma, podemos criar umSet somente leitura usando o métodosetOf()e leitura-gravaçãoMutableSet usandomutableSetOf():

val theSet = setOf("one", "two", "three")

val theMutableSet = mutableSetOf("one", "two", "three")

2.3. Map

Também podemos criar umMap somente leitura usando o métodomapOf()e leitura-gravaçãoMutableMap usandomutableMapOf():

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. Operadores Úteis

A API de coleções do Kotlin é muito mais rica do que a que podemos encontrar em Java - ela vem com um conjunto de operadores sobrecarregados.

3.1. O operador “in”

Podemos usar a expressão “x in collection” que pode ser traduzida paracollection.contains(x):

@Test
fun whenSearchForExistingItem_thenFound () {
    val theList = listOf("one", "two", "three")

    assertTrue("two" in theList)
}

3.2. O operador“+”

Podemos um elemento ou coleção inteira para outro usando o operador "+":

@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. O operador“-“

Da mesma forma, podemos remover um elemento ou vários elementos usando o operador “-”:

@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. Outros métodos

Finalmente, exploraremos alguns métodos comuns de coleta. Em Java, se quiséssemos aproveitar métodos avançados, precisaríamos usar a APIStream.

No Kotlin, podemos encontrar métodos semelhantes disponíveis na API de coleções.

Podemos obter uma sublista de um determinadoList:

@Test
fun whenSliceCollection_thenSuccess () {
    val theList = listOf("one", "two", "three")
    val resultList = theList.slice(1..2)

    assertEquals(2, resultList.size)
    assertTrue(resultList.contains("two"))
}

Podemos facilmente remover todos os nulos de umList:

@Test
fun whenFilterNullValues_thenSuccess () {
    val theList = listOf("one", null, "two", null, "three")
    val resultList = theList.filterNotNull()

    assertEquals(3, resultList.size)
}

Podemos filtrar itens de coleção facilmente usando o filtro(),, que funciona de maneira semelhante ao métodofilter() da API JavaStream:

@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))
}

Podemos descartar os primeiros N itens:

@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"))
}

Podemos descartar os primeiros itens se eles satisfizerem a condição fornecida:

@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"))
}

Podemos agrupar elementos:

@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))
}

Podemos mapear todos os elementos usando a função fornecida:

@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])
}

Podemos usarflatmap() para nivelar coleções aninhadas. Aqui, estamos convertendoStrings em List<String> e evitando terminar comList<List<String>>:

@Test
fun whenApplyMultiOutputFunctionToAllItems_thenSuccess () {
    val theList = listOf("John", "Tom")
    val resultList = theList.flatMap{ it.toLowerCase().toList() }

    assertEquals(7, resultList.size)
}

Podemos realizar a operaçãofold/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. Conclusão

Exploramos a API de coleções de Kotlin e alguns dos métodos mais interessantes.

E, como sempre, o código-fonte completo pode ser encontradoover on GitHub.