kotlinbeginner
Collections — map, filter, groupBy, and More
Master Kotlin collections: functional transformations, aggregations, grouping, and partition operations.
kotlinPress ⌘/Ctrl + Shift + C to copy
data class Product(val name: String, val category: String, val price: Double, val inStock: Boolean)
fun main() {
val products = listOf(
Product("Laptop", "Electronics", 999.99, true),
Product("Phone", "Electronics", 699.99, true),
Product("Tablet", "Electronics", 449.99, false),
Product("Shirt", "Clothing", 29.99, true),
Product("Pants", "Clothing", 49.99, true),
Product("Shoes", "Clothing", 89.99, false),
Product("Python Book", "Books", 39.99, true),
Product("Kotlin Book", "Books", 44.99, true)
)
// filter + map
val availableNames = products
.filter { it.inStock }
.map { it.name }
println("Available: $availableNames")
// groupBy
val byCategory = products.groupBy { it.category }
byCategory.forEach { (cat, items) ->
println("$cat: ${items.size} items")
}
// partition — splits into (match, noMatch)
val (inStock, outOfStock) = products.partition { it.inStock }
println("In stock: ${inStock.size}, Out: ${outOfStock.size}")
// associate / associateBy
val priceMap = products.associate { it.name to it.price }
println("Laptop: ${priceMap["Laptop"]}")
// flatMap
val tags = listOf(
listOf("kotlin", "jvm"),
listOf("kotlin", "android"),
listOf("java", "jvm")
)
val uniqueTags = tags.flatMap { it }.distinct()
println("Tags: $uniqueTags")
// Aggregations
println("Total value: ${products.sumOf { it.price }}")
println("Avg price: ${products.map { it.price }.average()}")
println("Most expensive: ${products.maxByOrNull { it.price }?.name}")
println("Cheapest: ${products.minByOrNull { it.price }?.name}")
// fold / reduce
val total = products.fold(0.0) { acc, p -> acc + p.price }
println("Fold total: $total")
val csv = products.map { it.name }.reduce { acc, name -> "$acc,$name" }
println("CSV: $csv")
// Chained operations
val summary = products
.filter { it.inStock }
.groupBy { it.category }
.mapValues { (_, items) ->
mapOf(
"count" to items.size,
"total" to items.sumOf { it.price },
"avg" to items.map { it.price }.average()
)
}
summary.forEach { (cat, stats) -> println("$cat: $stats") }
// Sequence (lazy) for large collections
val first3Expensive = products.asSequence()
.filter { it.inStock }
.sortedByDescending { it.price }
.take(3)
.map { "${it.name}: \$${it.price}" }
.toList()
println("Top 3: $first3Expensive")
// zip / unzip
val names = listOf("a", "b", "c")
val scores = listOf(10, 20, 30)
val pairs = names.zip(scores)
println("Zipped: $pairs") // [(a, 10), (b, 20), (c, 30)]
// windowed / chunked
val nums = (1..10).toList()
println("Chunked: ${nums.chunked(3)}")
println("Windowed: ${nums.windowed(3, 2)}")
}Use Cases
- Data processing and transformation pipelines
- Report generation from collections
- Functional data manipulation patterns
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
kotlinbeginner
Collection Transformations and Aggregations
Master Kotlin collection operations: groupBy, partition, associate, zip, windowed, and aggregate.
Best for: Data aggregation and reporting
#kotlin#collections
kotlinbeginner
Null Safety — Elvis, Safe Call, and let
Master Kotlin null safety: safe calls, Elvis operator, let/also scoping, and smart casts.
Best for: Safe navigation through nullable chains
#kotlin#null-safety
kotlinbeginner
Data Classes — Copy, Destructure, and Equals
Use data classes for immutable models: auto-generated equals, hashCode, copy, and destructuring.
Best for: Immutable domain models and DTOs
#kotlin#data-class
kotlinbeginner
Scope Functions — let, run, apply, also, with
Master Kotlin scope functions: when to use let, run, apply, also, and with for concise code.
Best for: Object initialization and configuration
#kotlin#scope-functions