Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Other Operations

Properties & Methods

Arrays, lists, sets and maps all have a size property that tells you how many elements are in a collection. In the case of maps, size is the number of key-value pairs held in the map.

Lists, sets and maps all have an isEmpty() method that returns true if collection size is zero, false if it is non-zero.

Lists have indexOf() and lastIndexOf() methods that can be used to find the first and last occurrence of a particular value in the list. These will return the index of the value you seek, or -1 if it couldn’t be found.

val words = listOf("Apple", "Orange", "Apple", "Kiwi")

println(words.size)
println(words.isEmpty())
println(words.lastIndexOf("Apple"))
println(words.indexOf("Banana"))

Extension Functions

Much of the useful functionality of collections is provided via extension functions. Many of these functions rely on lambda expressions to maximize their flexibility, so we will defer discussion of those until we cover that topic, but here are a few examples of what you can do without needing lambdas.

  • If you have an array, list or set whose elements are of a numeric type, then you can use the min(), max(), sum() and average() functions to compute the minimum, maximum, sum and average (arithmetic mean) of those numbers.

  • Given an array or list, you can use the reversed() function to get a new list with the elements in reverse order. You can also used sorted() and sortedDescending() to get new lists whose elements have been sorted into their natural ascending and descending order, respectively.

  • The chunked() function can be invoked on lists or sets to ‘chunk’ their contents into a list of lists, each of a given size. For example, the code below groups the contents of numbers into chunks with a maximum size of 3. When run, it prints [[9, 3, 6], [2, 8, 5], [1]].

    val numbers = listOf(9, 3, 6, 2, 8, 5, 1)
    val chunks = numbers.chunked(3)
    println(chunks)
    

    [Run this code]

  • The distinct() function can be invoked on arrays and lists. It returns a list in which duplicate values have been removed.

  • The shuffled() function can be invoked on a list to get a new list in which the elements have been reordered pseudo-randomly. If the list is mutable and you prefer to reorder its elements in place, you can use shuffle() instead.

These are just a few examples. See the operations overview in the offical language documentation, or the API reference material, for more details.