You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Kotlin/Java实现Map转List后先按值再按键排序?

Kotlin 实现

Kotlin 标准库直接提供了简洁的实现方式,用sortedWith配合compareBy就能搞定需求:

val map = mapOf("b" to 2, "a" to 1, "c" to 2, "d" to 3)
// 转换为排序后的键值对条目列表
val sortedEntryList = map.entries.sortedWith(compareBy({ it.value }, { it.key }))

// 如果需要转成Pair类型的列表
val sortedPairList = map.toList().sortedWith(compareBy({ it.second }, { it.first }))

compareBy会优先按第一个参数(值)排序,当值相同时,自动使用第二个参数(键的字母顺序)进行二次排序。

Java 实现

Java 8及以上可以借助Stream API和Comparator的链式调用实现,代码示例:

import java.util.*;
import java.util.stream.Collectors;

public class MapSortExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("b", 2);
        map.put("a", 1);
        map.put("c", 2);
        map.put("d", 3);

        // 转换为排序后的键值对条目列表
        List<Map.Entry<String, Integer>> sortedList = map.entrySet()
                .stream()
                .sorted(Comparator.comparing(Map.Entry::getValue)
                        .thenComparing(Map.Entry::getKey))
                .collect(Collectors.toList());
    }
}

这里Comparator.comparing先按值排序,thenComparing追加键的自然排序(String的默认比较逻辑就是字母顺序),完美匹配你的排序需求。

内容的提问来源于stack exchange,提问作者Kripthonite

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 23:05:25