Standard Library
Overview
Kotlin standard library provides rich functions, classes, and extensions covering collection operations, string processing, mathematical operations, I/O operations, and more. This chapter provides a detailed introduction to the core features and best practices of the Kotlin standard library.
Collection Operation Functions
Transformation Operations
kotlin
fun main() {
println("=== Collection Transformation Operations ===")
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val words = listOf("apple", "banana", "cherry", "date", "elderberry")
// map - Transform each element
val squared = numbers.map { it * it }
val lengths = words.map { it.length }
val upperCase = words.map { it.uppercase() }
println("Original numbers: $numbers")
println("Squared: $squared")
println("Word lengths: $lengths")
println("Uppercase words: $upperCase")
// mapIndexed - Transform with index
val indexedSquares = numbers.mapIndexed { index, value ->
"[$index]: ${value * value}"
}
println("Indexed squares: $indexedSquares")
// mapNotNull - Transform and filter null
val strings = listOf("1", "2", "abc", "4", "def")
val validNumbers = strings.mapNotNull { it.toIntOrNull() }
println("Valid numbers: $validNumbers")
// flatMap - Flatten mapping
val nestedLists = listOf(listOf(1, 2), listOf(3, 4), listOf(5, 6))
val flattened = nestedLists.flatMap { it }
println("Flattened: $flattened")
// flatten - Direct flattening
val directFlattened = nestedLists.flatten()
println("Direct flattened: $directFlattened")
// associate - Create mapping
val wordToLength = words.associate { it to it.length }
val indexToWord = words.associateBy { it.first() }
val wordToUpper = words.associateWith { it.uppercase() }
println("Word to length: $wordToLength")
println("First char to word: $indexToWord")
println("Word to uppercase: $wordToUpper")
}Filtering Operations
kotlin
fun main() {
println("=== Collection Filtering Operations ===")
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val words = listOf("apple", "banana", "cherry", "date", "elderberry", "fig")
val mixedList = listOf(1, "hello", 2.5, true, null, "world")
// filter - Basic filtering
val evenNumbers = numbers.filter { it % 2 == 0 }
val longWords = words.filter { it.length > 5 }
println("Even numbers: $evenNumbers")
println("Long words: $longWords")
// filterIndexed - Filter with index
val evenIndexElements = numbers.filterIndexed { index, _ -> index % 2 == 0 }
println("Elements at even indices: $evenIndexElements")
// filterNot - Negative filtering
val oddNumbers = numbers.filterNot { it % 2 == 0 }
println("Odd numbers: $oddNumbers")
// filterNotNull - Filter null values
val nonNullItems = mixedList.filterNotNull()
println("Non-null items: $nonNullItems")
// filterIsInstance - Type filtering
val strings = mixedList.filterIsInstance<String>()
val numbers2 = mixedList.filterIsInstance<Number>()
println("Strings: $strings")
println("Numbers: $numbers2")
// partition - Partitioning
val (evens, odds) = numbers.partition { it % 2 == 0 }
println("Partition - Even: $evens, Odd: $odds")
// take/drop series
val firstThree = numbers.take(3)
val lastThree = numbers.takeLast(3)
val withoutFirstThree = numbers.drop(3)
val withoutLastThree = numbers.dropLast(3)
println("First 3: $firstThree")
println("Last 3: $lastThree")
println("Without first 3: $withoutFirstThree")
println("Without last 3: $withoutLastThree")
// takeWhile/dropWhile - Conditional take/drop
val takeWhileSmall = numbers.takeWhile { it < 5 }
val dropWhileSmall = numbers.dropWhile { it < 5 }
println("Take while < 5: $takeWhileSmall")
println("Drop while < 5: $dropWhileSmall")
}Aggregation Operations
kotlin
fun main() {
println("=== Collection Aggregation Operations ===")
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val words = listOf("apple", "banana", "cherry", "date")
val emptyList = emptyList<Int>()
// Basic aggregation
println("Number list: $numbers")
println("Sum: ${numbers.sum()}")
println("Average: ${numbers.average()}")
println("Max: ${numbers.maxOrNull()}")
println("Min: ${numbers.minOrNull()}")
println("Count: ${numbers.count()}")
// sumOf - Custom sum
val totalLength = words.sumOf { it.length }
println("Total word length: $totalLength")
// maxBy/minBy - Get extreme value by condition
val longestWord = words.maxByOrNull { it.length }
val shortestWord = words.minByOrNull { it.length }
println("Longest word: $longestWord")
println("Shortest word: $shortestWord")
// reduce - Reduction operation
val product = numbers.reduce { acc, n -> acc * n }
println("Product: $product")
// fold - Reduction with initial value
val sumWithInitial = numbers.fold(100) { acc, n -> acc + n }
val concatenated = words.fold("Words: ") { acc, word -> "$acc$word " }
println("Sum with initial value: $sumWithInitial")
println("Concatenated string: $concatenated")
// Safe operations (handling empty collections)
println("Empty list max: ${emptyList.maxOrNull()}")
println("Empty list sum: ${emptyList.sum()}")
// reduceOrNull/foldOrNull - Safe reduction
val safeProduct = emptyList.reduceOrNull { acc, n -> acc * n }
println("Empty list safe product: $safeProduct")
// Grouping aggregation
val groupedByLength = words.groupBy { it.length }
val lengthCounts = words.groupingBy { it.length }.eachCount()
println("Grouped by length: $groupedByLength")
println("Length counts: $lengthCounts")
// Complex aggregation example
data class Student(val name: String, val grade: Int, val subject: String)
val students = listOf(
Student("Alice", 85, "Math"),
Student("Bob", 92, "Math"),
Student("Charlie", 78, "Science"),
Student("Diana", 95, "Math"),
Student("Eve", 88, "Science")
)
val mathAverage = students
.filter { it.subject == "Math" }
.map { it.grade }
.average()
val topStudent = students.maxByOrNull { it.grade }
val subjectAverages = students
.groupBy { it.subject }
.mapValues { (_, students) -> students.map { it.grade }.average() }
println("Math average: ${"%.1f".format(mathAverage)}")
println("Top student: ${topStudent?.name} (${topStudent?.grade})")
println("Subject averages: $subjectAverages")
}String Operations
String Processing Functions
kotlin
fun main() {
println("=== String Processing Functions ===")
val text = " Hello, Kotlin World! "
val multilineText = """
Line 1
Line 2
Line 3
""".trimIndent()
// Basic operations
println("Original text: '$text'")
println("Length: ${text.length}")
println("Trimmed: '${text.trim()}'")
println("Uppercase: ${text.uppercase()}")
println("Lowercase: ${text.lowercase()}")
// Check operations
println("Is empty: ${text.isEmpty()}")
println("Is blank: ${text.isBlank()}")
println("Contains 'Kotlin': ${text.contains("Kotlin")}")
println("Starts with 'Hello': ${text.startsWith("Hello")}")
println("Ends with '!': ${text.endsWith("!")}")
// Find operations
println("Position of 'Kotlin': ${text.indexOf("Kotlin")}")
println("Last position of 'l': ${text.lastIndexOf("l")}")
// Replace operations
println("Replace 'Kotlin' with 'Java': ${text.replace("Kotlin", "Java")}")
println("Replace first 'l': ${text.replaceFirst("l", "L")}")
// Split operations
val parts = text.trim().split(" ")
println("Split result: $parts")
val csvData = "apple,banana,cherry"
val fruits = csvData.split(",")
println("CSV split: $fruits")
// Substring operations
println("Substring[2,7]: '${text.substring(2, 7)}'")
println("From index 7: '${text.substring(7)}'")
// Multiline text processing
println("Multiline text:")
println(multilineText)
val lines = multilineText.lines()
println("Line count: ${lines.size}")
println("Lines: $lines")
// String building
val builder = StringBuilder()
builder.append("Hello")
builder.append(" ")
builder.append("World")
println("StringBuilder result: $builder")
// Using buildString
val builtString = buildString {
append("Kotlin")
append(" is")
append(" awesome!")
}
println("buildString result: $builtString")
}String Templates and Formatting
kotlin
fun main() {
println("=== String Templates and Formatting ===")
val name = "Alice"
val age = 25
val score = 95.5
// Basic string templates
println("Name: $name")
println("Age: $age")
println("Score: $score")
// Expression templates
println("Age next year: ${age + 1}")
println("Name length: ${name.length}")
println("Is adult: ${age >= 18}")
// Complex expressions
val message = "User $name (${age} years old) has a score of $score${if (score >= 90) " - Excellent!" else ""}"
println(message)
// Raw string templates
val json = """
{
"name": "$name",
"age": $age,
"score": $score
}
""".trimIndent()
println("JSON output:")
println(json)
}Next: Learning Resources to find more Kotlin learning materials