Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Collection Operations

Kotlin Collection Operations

Kotlin's standard library provides a full suite of chained operations for collections, letting you write common tasks such as filtering, transforming, aggregating, sorting, grouping, and finding in a single expression.

The vast majority of these functions return a new collection and do not modify the original, so you can chain them with confidence.

This chapter explains the most commonly used collection operations in seven categories, with runnable examples and real output for each function.


Filtering

Filtering operations select elements by a condition; the result is a new list and the original collection stays unchanged.

function Purpose Return Type
filter Keeps elements for which the lambda returns true List
filterNot Keeps elements for which the lambda returns false, the opposite of filter List
filterNotNull Removes all nulls and narrows the element type from T? to T List
partition Splits into two lists by a condition: "matching" and "non-matching" Pair, List>

Example

fun main

(

)

{

    val numbers

=

listOf

(

1

,

2

,

3

,

4

,

5

,

6

)

   

// filter: keep only even numbers

    val evens

=

numbers.

filter

{

it

%

2

==

0

}

    println

(

"Even numbers: $evens"

)

   

// filterNot: keep elements that don't match the condition, equivalent to filter { !... }

    val odds

=

numbers.

filterNot

{

it

%

2

==

0

}

    println

(

"Odd numbers: $odds"

)

   

// filterNotNull: removes nulls; the result type automatically becomes List

    val raw

=

listOf

(

"runoob"

,

null

,

"RUNOOB"

,

null

,

"kotlin"

)

    val clean

:

List

<

String

=

raw.

filterNotNull

(

)

    println

(

"After removing nulls: $clean"

)

   

// partition: get two groups at once, received via a destructuring declaration

    val

(

big, small

)

=

numbers.

partition

{

it

3

}

    println

(

"Greater than 3: $big"

)

    println

(

"Less than or equal to 3: $small"

)

}



偶数:[2, 4, 6]

奇数:[1, 3, 5]

去空后:[runoob, RUNOOB, kotlin]

大于 3:[4, 5, 6]

小于等于 3:[1, 2, 3]

Tip:The value of filterNotNull isn't just removing nulls; it also narrows the type from List to List, so later code no longer needs to write !! or ?.。


Mapping

Mapping transforms each element of a collection into another value by a rule; the number of elements usually stays the same (except for mapNotNull and flatMap).

function Purpose Result length
map Applies a transform to each element, producing a new list of the same length Same as the original collection
mapNotNull Keeps only non-null transform results, equivalent to map + filterNotNull Less than or equal to the original length
mapIndexed Also gets the element index during transformation; lambda parameters are (index, element) Same as the original collection
flatMap First produces a collection from each element, then flattens all results into one level Equal to the sum of the lengths of all sub-collections

Example

fun main

(

)

{

    val words

=

listOf

(

"runoob"

,

"kotlin"

)

   

// map: turn each string into its length

    println

(

words.

map

{

it.

length

}

)

   

// map: turn each string into uppercase

    println

(

words.

map

{

it.

uppercase

(

)

}

)

   

// mapNotNull: returns null when conversion fails; these nulls are automatically discarded

    val mixed

=

listOf

(

"1"

,

"x"

,

"3"

)

    println

(

mixed.

mapNotNull

{

it.

toIntOrNull

(

)

}

)

   

// mapIndexed: get both the index and the element

    println

(

words.

mapIndexed

{

index, word

->

"$index:$word"

}

)

    val nested

=

listOf

(

listOf

(

1

,

2

)

, listOf

(

3

,

4

)

)

   

// flatten: flatten a "list of lists" by one level

    println

(

nested.

flatten

(

)

)

   

// flatMap: transform then flatten in one step

    println

(

nested.

flatMap

{

inner

->

inner.

map

{

it

10

}

}

)

}



[6, 6]

[RUNOOB, KOTLIN]

[1, 3]

[0:runoob, 1:kotlin]

[1, 2, 3, 4]

[10, 20, 30, 40]


Aggregation

Aggregation reduces an entire collection to a single value, such as a sum, average, or maximum, and is the most commonly used group of functions for statistical logic.

function Purpose Behavior on an empty collection
fold Starts from an initial value and accumulates element by element Returns the initial value
reduce Uses the first element as the starting point; no initial value Throws UnsupportedOperationException
sum Sums a collection of numbers returns 0
sumOf First extracts values with a selector, then sums; supports Int, Long, Double, and BigDecimal returns 0
average Computes the average; the result is always a Double Throws NoSuchElementException
maxOrNull Returns the largest element, or null for an empty collection Returns null
minOrNull Returns the smallest element, or null for an empty collection Returns null

Example

fun main

(

)

{

    val numbers

=

listOf

(

1

,

2

,

3

,

4

)

   

// fold: the accumulator starts at the initial value 10 and adds each element in turn

    println

(

"fold:${numbers.fold(10) { acc, n -> acc + n }}"

)

   

// reduce: no initial value; uses the first element 1 as the starting point and multiplies successively

    println

(

"reduce:${numbers.reduce { acc, n -> acc * n }}"

)

    println

(

"sum:${numbers.sum()}"

)

   

// sumOf: first takes the length of each element, then sums

    println

(

"sumOf length: ${listOf("

runoob

", "

kotlin

").sumOf { it.length }}"

)

    println

(

"average:${numbers.average()}"

)

    println

(

"max:${numbers.maxOrNull()}"

)

    println

(

"min:${numbers.minOrNull()}"

)

   

// On an empty collection fold is safe and maxOrNull returns null, while reduce and average throw exceptions

    val empty

=

emptyList

<

Int

(

)

println

(

"Empty collection fold: ${empty.fold(0) { acc, n -> acc + n }}"

)

    println

(

"Empty collection max: ${empty.maxOrNull()}"

)

}



fold:20

reduce:24

sum:10

sumOf 长度:12

average:2.5

max:4

min:1

空集合 fold:0

空集合 max:null

Note:maxOrNull() The difference between minOrNull() Used since Kotlin 1.4; older versions simply called it max() / min(); they were removed in 1.7. The old forms throw exceptions on empty collections, while the new ones return null, which is safer.

sumOf Also provided since Kotlin 1.4, it automatically chooses the summing method, Int, Long, Double, and so on, based on the selector's return type.


Sorting

Sorting functions all return a new list and leave the original order unchanged, which differs from MutableList.sort() in-place sorting.

Example

// A data class for sorting, defined at the top level

data

class

Site

(

val name

:

String

, val age

:

Int

)

fun main

(

)

{

    val sites

=

listOf

(

        Site

(

"runoob"

,

12

)

,

        Site

(

"kotlin"

,

9

)

,

        Site

(

"RUNOOB"

,

20

)

   

)

   

// sortedBy: ascending order by a selector

    println

(

sites.

sortedBy

{

it.

age

}

.

map

{

it.

name

}

)

   

// sortedByDescending: descending order by a selector

    println

(

sites.

sortedByDescending

{

it.

age

}

.

map

{

it.

name

}

)

   

// sortedWith: custom comparator, first by name then by age

    println

(

sites.

sortedWith

(

compareBy

<

Site

{

it.

name

}

.

thenBy

{

it.

age

}

)

.

map

{

it.

name

}

)

   

// sorted: natural ordering of the elements themselves, only for Comparable types

    println

(

listOf

(

3

,

1

,

4

)

.

sorted

(

)

)

   

// reversed: simply reverses the order, without any comparison

    println

(

listOf

(

3

,

1

,

4

)

.

reversed

(

)

)

   

// shuffled: randomly shuffles; the set of elements is unchanged, and the order may differ on each run

    val shuffled

=

listOf

(

1

,

2

,

3

,

4

,

5

)

.

shuffled

(

)

    println

(

"After shuffled, sorting restores: ${shuffled.sorted()}"

)

}



[kotlin, runoob, RUNOOB]

[RUNOOB, runoob, kotlin]

[RUNOOB, kotlin, runoob]

[1, 3, 4]

[4, 1, 3]

shuffled 后排序还原:[1, 2, 3, 4, 5]

String comparison in lexicographic order is case-sensitive; uppercase letters have smaller code points than lowercase ones, so RUNOOB comes before kotlin .


Grouping and Chunking

Grouping reorganizes elements into a Map by a key, while chunking splits a list into fixed-size pieces or sliding windows.

function Purpose Return Type
groupBy Groups by key, collecting elements with the same key into a list Map>
associateBy Indexes by key; when keys repeat, later ones overwrite earlier ones Map
chunked Splits into chunks of fixed length; the last chunk may be shorter List>
windowed Generates sliding windows of fixed length, with a default step of 1 List>

Example

// A data class for grouping, defined at the top level

data

class

Site

(

val name

:

String

, val country

:

String

)

fun main

(

)

{

    val sites

=

listOf

(

        Site

(

"runoob"

,

"CN"

)

,

        Site

(

"kotlin"

,

"US"

)

,

        Site

(

"RUNOOB"

,

"CN"

)

   

)

   

// groupBy: the key is country, and the value is the list of sites in that country

    val byCountry

=

sites.

groupBy

{

it.

country

}

    println

(

byCountry.

mapValues

{

(

_, list

)

->

list.

map

{

it.

name

}

}

)

   

// associateBy: use name as the key to get the Site object directly

    println

(

sites.

associateBy

{

it.

name

}

.

keys

)

    val numbers

=

listOf

(

1

,

2

,

3

,

4

,

5

)

   

// chunked: group every 2 elements; keep the final group even if it has fewer than 2

    println

(

numbers.

chunked

(

2

)

)

   

// windowed: sliding windows of length 3, with step = 1 by default

    println

(

numbers.

windowed

(

3

)

)

   

// step = 2, and allow a trailing window shorter than the full length

    println

(

numbers.

windowed

(

3

, step

=

2

, partialWindows

=

true

)

)

}



{CN=[runoob, RUNOOB], US=[kotlin]}

[runoob, kotlin, RUNOOB]

[[1, 2], [3, 4], [5]]

[[1, 2, 3], [2, 3, 4], [3, 4, 5]]

[[1, 2, 3], [3, 4, 5], [5]]

Difference:Keys in groupBy can repeat, with one key mapping to multiple elements; keys in associateBy must be unique, and only the last element is kept when a key repeats. Use associateBy when you need "one key maps to one object" and groupBy when you need "one key maps to a group of objects".

chunked The difference between windowed Available since Kotlin 1.2, they are very convenient for pagination and sliding-window statistics.


Finding and Checking

Finding functions locate elements, while checking functions answer questions like "is there an element that satisfies the condition?"

function Purpose Behavior When Nothing Is Found
find Returns the first element that satisfies the condition Returns null
first Returns the first element, optionally with a condition Throws NoSuchElementException
firstOrNull Same as first, but returns null when nothing is found Returns null
last Returns the last element, optionally with a condition Throws NoSuchElementException
any Whether any element satisfies the condition Returns false
all Whether all elements satisfy the condition Returns true
none Whether no element satisfies the condition Returns true
count Counts the elements, optionally with a condition returns 0

Example

fun main

(

)

{

    val numbers

=

listOf

(

2

,

4

,

6

,

7

,

8

)

   

// find: the first odd number, or null if none is found

    println

(

numbers.

find

{

it

%

2

==

1

}

)

    println

(

numbers.

find

{

it

100

}

)

    println

(

numbers.

first

(

)

)

    println

(

numbers.

first

{

it

5

}

)

    println

(

numbers.

last

(

)

)

    println

(

numbers.

last

{

it

<

6

}

)

// any / all / none use short-circuit evaluation, stopping the traversal as soon as the result is determined

    println

(

numbers.

any

{

it

7

}

)

    println

(

numbers.

all

{

it

%

2

==

0

}

)

    println

(

numbers.

none

{

it

<

0

}

)

println

(

numbers.

count

{

it

%

2

==

0

}

)

}



7

null

2

6

8

4

true

false

true

4

Note:first()、last() They throw an exception on an empty collection or when no element matches. Unless you are sure a value exists, prefer the null-safe alternatives firstOrNull() and find()so that the return type itself expresses "there may be none".


Joining

joinToString Joins a collection into a single string; it is the most commonly used finishing function for logging and text generation.

Parameters Default value Description
separator ", " The separator between elements
prefix "" The overall prefix
postfix "" The overall suffix
limit -1 The maximum number of elements to join; -1 means unlimited
truncated "..." The string appended when the result is truncated
transform None A lambda that transforms each element before joining

Example

fun main

(

)

{

    val numbers

=

listOf

(

2

,

4

,

6

,

7

,

8

)

   

// The default separator is ", "

    println

(

numbers.

joinToString

(

)

)

   

// Custom prefix, suffix, and separator

    println

(

numbers.

joinToString

(

separator

=

"-"

, prefix

=

"["

, postfix

=

"]"

)

)

   

// Join only the first 3 elements and use an ellipsis for the rest

    println

(

numbers.

joinToString

(

limit

=

3

, truncated

=

"..."

)

)

   

// transform: shape each element into the desired form before joining

    println

(

numbers.

joinToString

{

"n=$it"

}

)

}



2, 4, 6, 7, 8

[2-4-6-7-8]

2, 4, 6, ...

n=2, n=4, n=6, n=7, n=8


Common questions

Here is a summary of the most common pitfalls beginners hit when working with collections.

Problem Reason Recommendation
The original list is unchanged after sorted() sorted returns a new list and does not modify the original collection Capture the return value, or use sort() on a MutableList
reduce crashes on an empty collection reduce has no initial value, so there is no starting point Use fold instead, or check that the collection is not empty first
average returns a Double An average can naturally have a fractional part When you need an integer result, compute it yourself with sum() / count()
A null returned inside map still remains in the result map does not filter out nulls Use mapNotNull when you need to filter them out
The filter condition is written backwards "Keep" was mistaken for "exclude" Use filterNot to express exclusion explicitly