Useful functions for Kotlin Collections.
fun main() {
val setInts = setOf(10, 15, 19, 5, 3, -22)
println(setInts.filter { it % 2 != 0 }) // Odd numbers only
val immutableMap = mapOf(1 to Car3("green", "Toyota", 2015),
2 to Car3("red", "Ford", 2016),
3 to Car3("silver", "Honda", 2013),
17 to Car3("red", "BMW", 2015),
8 to Car3("green", "Ford", 2010)
)
println("2016 cars only: ${immutableMap.filter { it.value.year == 2016 }}") // 2016 cars only
val mutableMap = mutableMapOf(1 to Car3("green", "Toyota", 2015), 2 to Car3("red", "Ford", 2016), 3 to Car3("silver", "Honda", 2013))
mutableMap.filter { it.value.colour == "silver" }
println(mutableMap) // Map hasn't changed by being filtered. Filter creates new instance of the map.
// Add 10 to every element and create new
val ints = arrayOf(1, 2, 3, 4, 5)
val add10List: MutableList<Int> = mutableListOf()
for (i in ints) {
add10List.add(i + 10)
}
println("Add10List: ${add10List}")
// The Kotlin way - using the map FUNCTION (not Collection)
val add10List2 = ints.map { it + 10 }
println("Add10List2: ${add10List2}")
// Create a List that contains all the years of the Cars in our Map
val carYearsList = immutableMap.map { it.value.year }
println("Car years list: ${carYearsList}")
// You can chain filter and map functions together:
println("Ford cars only: ${immutableMap.filter { it.value.model == "Ford" }}") // Ford cars only
println("Ford car colours: ${immutableMap.filter { it.value.model == "Ford" }.map { it.value.colour}}") // Ford car colours
// If all the elements in a Collection match a condition:
println(immutableMap.all { it.value.year > 2014 }) // Are all cars modern (post-2015)?
println(immutableMap.any { it.value.year > 2014 }) // Are any cars modern (post-2015)?
println(immutableMap.count { it.value.year > 2014 }) // How many cars are modern (post-2015)?
// To find value that matches we can move them into a List and use the find function
val cars = immutableMap.values
println("First modern car: ${cars.find { it.year > 2014}}") // Finds first item in List that satisfies condition
println("Cars grouped by colour: ${cars.groupBy { it.colour }}") // Group cars by colour
println("Cars sorted by year: ${cars.sortedBy { it.year }}") // Sorted by year
println("Sorted by key: ${immutableMap.toSortedMap()}") // Sorted by key
}
data class Car3(val colour: String, val model: String, val year: Int)
