A study note based on Kotlin Collections Document.

1 Introduction

Kotlin provides collection types of List, Set and Map. There are a read-only and a mutable interface. Read-only collection types are covariant.

List and Set are subclasses of Collection. Use listOf and setOf to create immutable list and set. Use mutableListOf and mutableSetOf to create mutable list and set. The default implementation of Set is LinkedHashSet that preserves the order of elements insertion.

Map<K, V> is not a subclass of Collection. Use mapOf and mutableMapOf to create immutable and mutable set. The default implementation LinkedHashMap keeps the order of elements insertion.

You can use concerte type such as ArrayList, LinkedList to create a collection instance.

To create a copy or convert to a different type, use toList, toMutableList, toSet etc.

Range implements Iterable and is eager. Sequence is lazy.

Use generateSequence to create a sequence from a function. Use sequence to create a sequence in chunks.

2 Operations

  • Transofrmation: map, zip, associateWith, associateBy, flatten
  • Filtering: filter, filterNot, partition, any, none, all
  • Plus and Minus: +, -
  • Grouping: groupBy, a group support eachCount, fold, reduce, aggregate
  • Slicing: slice, take, drop, takeWhile, takeLastWhile, chunked, windowed
  • Others: search, ordering, aggregate