DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Kotlin Collections Guide — map, filter, groupBy & Sequences

Kotlin's collection functions transform data efficiently. Master map, filter, groupBy, and the lazy Sequence API.

Map Operations

Transform collection elements:

val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }  // [2, 4, 6, 8, 10]

val users = listOf(
    User("Alice", 25),
    User("Bob", 30)
)
val names = users.map { it.name }  // ["Alice", "Bob"]

val flatMapped = listOf(1, 2, 3).flatMap { num ->
    listOf(num, num * 10)
}  // [1, 10, 2, 20, 3, 30]

val mapNotNull = listOf(1, 2, null, 4).mapNotNull { it }  // [1, 2, 4]
Enter fullscreen mode Exit fullscreen mode

Filter Operations

Select elements by condition:

val numbers = listOf(1, 2, 3, 4, 5, 6)
val evens = numbers.filter { it % 2 == 0 }  // [2, 4, 6]

val (evens, odds) = numbers.partition { it % 2 == 0 }
// evens: [2, 4, 6], odds: [1, 3, 5]

val first = numbers.first { it > 3 }  // 4
val firstOrNull = numbers.firstOrNull { it > 10 }  // null
Enter fullscreen mode Exit fullscreen mode

GroupBy & Associates

Organize elements into groups:

val words = listOf("apple", "apricot", "banana", "blueberry")
val grouped = words.groupBy { it.first() }
// {'a': ["apple", "apricot"], 'b': ["banana", "blueberry"]}

val byLength = words.associateBy { it.length }
// {5: "apple", 7: "apricot", 6: "banana", 9: "blueberry"}

val sumByPrice = items.sumOf { it.price }
val maxPrice = items.maxByOrNull { it.price }
Enter fullscreen mode Exit fullscreen mode

Sorting Operations

Order collection elements:

val numbers = listOf(5, 2, 8, 1, 9)
val sorted = numbers.sorted()  // [1, 2, 5, 8, 9]

val users = listOf(
    User("Alice", 25),
    User("Bob", 20),
    User("Charlie", 30)
)
val byAge = users.sortedBy { it.age }
val byAgeDesc = users.sortedByDescending { it.age }

val custom = users.sortedWith(
    compareBy<User> { it.age }.thenBy { it.name }
)
Enter fullscreen mode Exit fullscreen mode

Chaining Operations

Combine multiple transformations:

val users = listOf(
    User("Alice", 25, 5000),
    User("Bob", 30, 6000),
    User("Charlie", 35, 7000)
)

val highEarners = users
    .filter { it.salary > 5500 }
    .map { it.name }
    .sorted()

val report = users
    .filter { it.age >= 30 }
    .groupBy { it.age }
    .mapValues { (_, group) ->
        group.sumOf { it.salary }
    }
Enter fullscreen mode Exit fullscreen mode

Sequence - Lazy Evaluation

Optimize large collections:

val numbers = (1..1000000).asSequence()
    .filter { it % 2 == 0 }
    .map { it * 2 }
    .take(5)
    .toList()

// Compared to eager evaluation:
val eagerNumbers = (1..1000000)
    .filter { it % 2 == 0 }
    .map { it * 2 }
    .take(5)
    .toList()
Enter fullscreen mode Exit fullscreen mode

With Sequence, the filter and map are only applied to the first 5 elements needed, not all 1 million.

List vs Sequence

When to use each:

// Use List for small collections or when you need multiple iterations
val list = listOf(1, 2, 3, 4, 5)
val even = list.filter { it % 2 == 0 }
val doubled = even.map { it * 2 }  // Multiple iterations

// Use Sequence for large collections or single-pass operations
val sequence = (1..1000000).asSequence()
    .filter { it % 2 == 0 }
    .map { it * 2 }
    .toList()
Enter fullscreen mode Exit fullscreen mode

Compose Usage with remember

Optimize Compose recompositions:

@Composable
fun UserList(users: List<User>) {
    val sortedUsers = remember(users) {
        users.sortedBy { it.name }
    }

    LazyColumn {
        items(sortedUsers.size) { index ->
            UserItem(sortedUsers[index])
        }
    }
}

@Composable
fun FilteredList(items: List<String>, filter: String) {
    val filtered = remember(items, filter) {
        items.asSequence()
            .filter { it.contains(filter) }
            .toList()
    }

    LazyRow {
        items(filtered) { item ->
            Text(item)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Collection mastery unlocks elegant, performant Kotlin code.

8 Android app templates available: Gumroad

Top comments (0)