[Kotlin] Working with Map
阿新 • • 發佈:2020-10-14
fun main(args: Array<String>) { val namesToAges = mapOf(Pair("Peter", 24), Pair("Roger", 42)) val namesToAges2 = mapOf( "Peter" to 24, "Roger" to 42 ) println(namesToAges == namesToAges2) // true println(namesToAges.keys) // [Peter, Roger]println(namesToAges.values) // [24, 42] println(namesToAges.entries) // [Peter=24, Roger=42] namesToAges.entries.forEach { println("${it.key} is ${it.value}") } /* * Peter is 24 Roger is 42 * */ val countryToInhabitants = mutableMapOf( "Germany" to 80_000_000,"USA" to 300_000_000 ) countryToInhabitants.put("Australia", 23_000_000) countryToInhabitants.putIfAbsent("USA", 23_000_000) // "usa" already exists println(countryToInhabitants.contains("USA")) // true println(countryToInhabitants.containsKey("France")) // false println(countryToInhabitants.containsValue(20_000_000)) //false println(countryToInhabitants.get("Germany")) println(countryToInhabitants.getOrDefault("France", 0)) // 0 }