Sobes.tech
Junior

What collection functions does the Kotlin language provide?

sobes.tech AI

Answer from AI

Kotlin offers a comprehensive set of extension functions for working with collections, which make the code more concise and readable. They can be conditionally divided into the following categories:

1. Filtering:

  • filter/filterNot: Returns a list of elements that match/do not match the predicate.
  • filterNotNull: Returns a list of all non-null elements.
  • filterIsInstance<T>: Returns a list of all elements that are instances of type T.

2. Transformation (Mapping):

  • map/mapIndexed: Transforms each element of the collection into a new element. mapIndexed also receives the index of the element.
  • mapNotNull/mapIndexedNotNull: Transforms each element, discarding null.
  • flatMap: Transforms each element into a collection and flattens them into a single collection.
  • zip: Creates a collection of pairs from elements of two collections with the same indices.

3. Aggregation (Reducing):

  • reduce/fold: Applies an operation to sequential elements of the collection, accumulating the result. fold takes an initial value.
  • sum, average, count, max, min: Basic aggregation functions.

4. Sorting:

  • sorted/sortedDescending: Returns a sorted collection.
  • sortedBy/sortedByDescending: Returns a sorted collection based on the result of applying a selector function.
  • reversed: Returns the list in reverse order.
  • shuffled: Returns a shuffled list.

5. Accessing elements:

  • first/firstOrNull: Returns the first element.
  • last/lastOrNull: Returns the last element.
  • find/findLast: Returns the first/last element matching the predicate.
  • elementAt/elementAtOrNull/elementAtOrElse: Returns the element at the specified index.
  • single/singleOrNull: Returns the single element if it exists.

6. Condition checks:

  • all/any: Checks if all/any elements satisfy the predicate.
  • none: Checks if no elements satisfy the predicate.
  • contains: Checks for the presence of an element.

7. Grouping:

  • groupBy: Groups elements by a key defined by a selector function.

8. Partitioning:

  • partition: Divides the collection into two parts: elements satisfying the predicate and those that do not.
  • chunked: Breaks the collection into chunks of a specified size.

9. Collection comparison:

  • equals: Compares the contents of two collections.
  • containsAll: Checks if the collection contains all elements of another collection.

10. Multiple operations:

  • intersect: Returns common elements of two collections.
  • subtract: Returns elements of the first collection not present in the second.
  • union: Returns all unique elements from both collections.

Examples of usage:

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6)

    // Filtering
    val evenNumbers = numbers.filter { it % 2 == 0 } // [2, 4, 6]

    // Transformation
    val squaredNumbers = numbers.map { it * it } // [1, 4, 9, 16, 25, 36]

    // Aggregation
    val sumOfNumbers = numbers.sum() // 21

    // Grouping
    val names = listOf("Alice", "Bob", "Charlie", "David")
    val groupedByNameLength = names.groupBy { it.length }
    // {5=[Alice, Charlie], 3=[Bob], 4=[David]}
}