簡體   English   中英

如何獲取 Kotlin Map 集合中的最后一個鍵或值

[英]How to get last Key or Value in Kotlin Map collection

如何獲取Kotlin Map集合中的最后一個鍵或值? 似乎不能通過使用索引值來完成。

在 Kotlin 中,可以使用 last() function 獲取 Map 集合中的最后一個元素。 這個 function 返回一個 Pair object,其中包含 Map 中最后一個元素的鍵和值。

下面是如何使用 last() 獲取 Map 中最后一個元素的示例:

val map = mapOf(1 to "one", 2 to "two", 3 to "three")

val lastElement = map.last()
println(lastElement)  // Output: 3=three

也可以使用 Map 的 entries 屬性獲取 Map 中所有鍵值對的列表,然后使用 last() function 獲取列表中的最后一個元素。

val map = mapOf(1 to "one", 2 to "two", 3 to "three")

val lastElement = map.entries.last()
println(lastElement)  // Output: 3=three

如果只想獲取最后一個元素的鍵或值,可以使用解構聲明從 Pair object 中提取它們。

val map = mapOf(1 to "one", 2 to "two", 3 to "three")

val (key, value) = map.last()
println("Key: $key, Value: $value")  // Output: Key: 3, Value: three

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM