Last Updated:

Kotlin collection cheat sheet

Kotlin collection cheat sheet

The most interesting points:

  • In addition to standard lists, hashmaps, and sets, Kotlin also has collection types such as linkedMap, linkedSet, sortedMap, and sortedSet. In fact, these are analogues of the same sets and hashmaps, but with the functions of saving a sequence of elements (linked) or automatic sorting (sorted).
  • In addition to functions for creating collections, the language also has a number of functions for copying them. For example, except for the standard method copyOf, methods are also available copyInto — copy all elements to another array, copyOfRange - copy a range of elements and toCollection - Copy all items to another collection.
  • When assigning collections, you can use methods to return default values: ifEmpty - Return the default value if the collection is empty. orEmpty - Return an empty collection if the current collection is null. requireNoNulls - Throws an exception IllegalArgumentExceptionif all items in the collection are null. listOfNotNull is an exception if at least one of the elements is null.
  • Functions toIntArray and asIntArray (as well as all other functions with similar names) differ in that the first creates a list with new items based on the original list, and the second creates a list of items - links to the items of the original list.
  • Record map. toList() equivalent to a record map. entries. map { it. toPair() }.
  • To access list items by indexes, you can use the function withIndex.
  • Most list modifier functions have an equivalent that does not change the list. For example, the function addthat adds an item to the list, there is an equivalent function plus, which returns a new list with the item added. Other examples: removeFirst — dropremoveLast — dropLast.
  • Kotlin allows you to combine collections in several ways. For example union creates a new collection in which only unique elements of the two collections are present, intersect – a new collection with elements that are present in both collections, substract is a collection of items that appear only in the first list. Function zip returns a collection whose element each item includes items from the first and second collections with the same index.
  • In addition to the well-known method map, designed to convert a collection of items of one type to a collection of items of another type, there are other functions: aggregate – combining several elements, associate is the binding of an element to a value, groupBy — grouping of elements, flatten – transformation of multidimensional collections into one-dimensional ones, chunked - Breakdown by category.