Kotlin 按值对 Map 进行排序的程序

示例:按值对映射进行排序

fun main(args: Array<String>) {

    var capitals = hashMapOf<String, String>()
    capitals.put("Nepal", "Kathmandu")
    capitals.put("India", "New Delhi")
    capitals.put("United States", "Washington")
    capitals.put("England", "London")
    capitals.put("Australia", "Canberra")

    val result = capitals.toList().sortedBy { (_, value) -> value}.toMap()

    for (entry in result) {
        print("Key: " + entry.key)
        println(" Value: " + entry.value)
    }
}

运行程序后,输出将是

Key: Australia Value: Canberra
Key: Nepal Value: Kathmandu
Key: England Value: London
Key: India Value: New Delhi
Key: United States Value: Washington

在上面的程序中,我们有一个名为 capitals 的变量,其中存储了国家及其各自首都的 HashMap

为了对映射进行排序,我们使用在一行中执行的一系列操作。

val result = capitals.toList().sortedBy { (_, value) -> value}.toMap()
  • 首先,使用 toList()capitals 转换为列表。
  • 然后,使用 sortedBy() 按值 { (_, value) -> value} 对列表进行排序。我们使用 _ 表示键,因为我们不使用它进行排序。
  • 最后,我们使用 toMap() 将其转换回映射,并存储在 result 中。

这是等效的 Java 代码:按值对映射进行排序的 Java 程序

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战