Post

Collection Operations in Kotlin

Collection Operations in Kotlin

Quick Reference Tables

Basic Operations

OperationDescriptionExampleReturns
filterKeep elements matching predicatelist.filter { it > 0 }List
filterNotRemove elements matching predicatelist.filterNot { it > 0 }List
mapTransform each elementlist.map { it * 2 }List
forEachIterate elementslist.forEach { print(it) }Unit
anyCheck if any matchlist.any { it > 0 }Boolean
allCheck if all matchlist.all { it > 0 }Boolean
noneCheck if none matchlist.none { it > 0 }Boolean
countCount elementslist.count { it > 0 }Int
findFirst matching or nulllist.find { it > 0 }E?
containsCheck if element existslist.contains(5)Boolean

Transformation Operations

OperationDescriptionExampleReturns
distinctUnique elementslist.distinct()List
sortedSort ascendinglist.sorted()List
sortedBySort by selectorlist.sortedBy { it.age }List
sortedDescendingSort descendinglist.sortedDescending()List
reversedReverse orderlist.reversed()List
flattenFlatten nested listslistOf(list1, list2).flatten()List
flatMapMap and flattenlist.flatMap { listOf(it, -it) }List
groupByGroup by keylist.groupBy { it.type }Map
associateCreate maplist.associate { it to it * 2 }Map
zipPair elementslist1.zip(list2)List

Aggregate Operations

OperationDescriptionExampleReturns
sumSum of elementslist.sum()Number
averageAverage of elementslist.average()Double
max/minMax/min elementlist.max()E?
maxBy/minByMax/min by selectorlist.maxBy { it.value }E?
reduceReduce to single valuelist.reduce { acc, e -> acc + e }E
foldReduce with initiallist.fold(0) { acc, e -> acc + e }R
joinToStringJoin to stringlist.joinToString(",")String
chunkedSplit into chunkslist.chunked(3)List
windowedSliding windowlist.windowed(3)List

Common Problem-Solving Patterns

Frequency Count

1
2
3
4
5
6
7
8
// Count occurrences
val freq = list.groupingBy { it }.eachCount()

// Top K frequent
val topK = freq.entries
    .sortedByDescending { it.value }
    .take(k)
    .map { it.key }

Window Operations

1
2
3
4
5
6
7
8
// Fixed size window
list.windowed(3) { window -> window.sum() }

// Sliding window with step
list.windowed(3, step = 2, partial = true)

// Running sum
list.runningFold(0) { acc, e -> acc + e }

Two Pointers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Find pair sum
fun findPairSum(list: List<Int>, target: Int): Pair<Int, Int>? {
    val sorted = list.sorted()
    var left = 0
    var right = sorted.lastIndex
    
    while (left < right) {
        val sum = sorted[left] + sorted[right]
        when {
            sum == target -> return sorted[left] to sorted[right]
            sum < target -> left++
            else -> right--
        }
    }
    return null
}

Set Operations

1
2
3
4
5
6
val set1 = setOf(1, 2, 3)
val set2 = setOf(3, 4, 5)

set1 intersect set2  // [3]
set1 union set2      // [1, 2, 3, 4, 5]
set1 subtract set2   // [1, 2]

Matrix Operations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Transpose matrix
val transposed = matrix.indices.map { i ->
    matrix[0].indices.map { j -> matrix[j][i] }
}

// Flatten 2D array
val flattened = matrix.flatten()

// Matrix multiplication using fold
val result = matrix1.map { row ->
    matrix2[0].indices.map { col ->
        row.indices.fold(0) { acc, i ->
            acc + row[i] * matrix2[i][col]
        }
    }
}

Performance Tips

  1. Use sequences for large collections with multiple operations:
    1
    2
    3
    4
    5
    
    list.asSequence()
     .filter { it > 0 }
     .map { it * 2 }
     .take(3)
     .toList()
    
  2. Prefer:
    • getOrNull() over try-catch
    • firstOrNull() over find()
    • any() over count() > 0
    • none() over count() == 0
  3. Chain Operations Efficiently: ```kotlin // ❌ Inefficient list.filter { it > 0 }.map { it * 2 }.filter { it < 10 }

// ✅ Better list.filter { it > 0 && it * 2 < 10 }.map { it * 2 } ```

Remember: Consider space-time tradeoffs when choosing between different collection operations. Some operations create new collections while others work in-place.

This post is licensed under CC BY 4.0 by the author.