Android中HashMap的使用:
HashMap的简单实例:
01.创建Map:
class MainActivity : AppCompatActivity() {
@RequiresApi(Build.VERSION_CODES.N)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val name = mapOf<String, String>("name" to "alfied", "sex" to "man", "age" to "27")
println(name.getValue("name"))
println(name.getOrDefault("weight", "70kg"))
println(name.minus("age"))
println(name.plus("height" to "180cm"))
}
}
02.MutableMap的数据增删改查
val m1 = mutableMapOf("name" to "alfred")
val m2 = mutableMapOf("sex" to "man", "age" to "27")
m1.put("身高", "128cm")
println(m1)
m1["体重"] = "70kg"
println(m1)
m1.remove("体重")
println(m1)
m1.putAll(m2)
println(m1)
m1.remove("体重", "70kg")
println(m1)
创建HashMap、LinkedMap、SortedMap
val hash = hashMapOf("name" to "alfred")
val linkedMap = linkedMapOf("age" to "27")
val treeMap = sortedMapOf("sex" to "man")
println(hash)
println(linkedMap)
println(treeMap)
HashMap的拓展实例:
01.HashMap以Key来进行排序
val map1 = sortedMapOf<String, Int>()
map1.put("Java", 30)
map1.put("Android", 40)
map1.put("C++", 15)
println(map1)
var comparator = kotlin.Comparator{key1: String, key2: String -> key2.compareTo(key1)}
val map2 = sortedMapOf<String, Int>(comparator)
map2.put("Java", 30)
map2.put("Android", 40)
map2.put("C++", 15)
println(map2)
02.HashMap以value来进行排序
var map3 = TreeMap<String, Int>()
map3.put("Java", 30)
map3.put("Android", 60)
map3.put("C++", 15)
map3.put("Kotlin", 100)
map3["C"] = 0
val mapSort = map3.entries.sortedBy { it.value}
.associateBy({it.key}, {it.value})
println(mapSort)
val mapDescSort = map3.entries.sortedByDescending { it.value }
.associateBy({it.key}, {it.value})
println(mapDescSort)
val toMap = map3.toList().sortedBy { it.second }.toMap()
println(toMap)
03.HashMap的遍历
val map4 = hashMapOf("name" to "Jack", "age" to "12", "sex" to "man")
val iter = map4.entries.iterator()
while(iter.hasNext()){
val entry = iter.next()
println(entry)
}
for(key in map4.keys) {
println("key = $key + value = ${map4.get(key)}")
}
map4.forEach {
println("key==${it.key}, value==${it.value}")
}
for ((key, value) in map4) {
println("key==$key, value==$value")
}
|