java-HashMap、TreeMap、LinkedHashMap、ArrayList、LinkedList使用笔记

背景

java 复制代码
Map<String, Integer> unsortedMap = new HashMap<>();  
unsortedMap.put("One", 1);  
unsortedMap.put("Two", 2);  
unsortedMap.put("Three", 3);  
unsortedMap.put("Four", 4);  

一、关于排序

  1. TreeMap:默认按照key排序
  2. 按照value排序,可使用如下代码
java 复制代码
List<Map.Entry<String, Integer>> list = new LinkedList<>(unsortedMap.entrySet());  
  
// Sort the list based on values  
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {  
    public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {  
        return (o1.getValue()).compareTo(o2.getValue());  
    }  
});  
  
// Convert list to map again  
Map<String, Integer> sortedMap = new LinkedHashMap<>();  
for (Map.Entry<String, Integer> entry : list) {  
    sortedMap.put(entry.getKey(), entry.getValue());  
}  
System.out.println("Sorted map by value: " + sortedMap);

二、关于转换

  1. HashMap转TreeMap
java 复制代码
Map<String, Integer> sortedMap = new TreeMap<>(unsortedMap);
  1. HashMap转LinkedList
java 复制代码
List<Map.Entry<String, Integer>> list = new LinkedList<>(unsortedMap.entrySet());  
相关推荐
大尚来也2 小时前
驾驭并发:.NET多线程编程的挑战与破局之道
java·前端·算法
dong__csdn2 小时前
jdk添加信任证书
java·开发语言
hhcccchh3 小时前
1.1 HTML 语义化标签(header、nav、main、section、footer 等)
java·前端·html
架构师老Y3 小时前
006、异步编程与并发模型:asyncio与高性能后端
python
随风,奔跑3 小时前
Spring Security
java·后端·spring
清水白石0083 小时前
《解锁 Python 潜能:从核心语法到 AI 服务层架构的工业级进阶与实战》
人工智能·python·架构
kcuwu.3 小时前
Python数据分析三剑客导论:NumPy、Pandas、Matplotlib 从入门到入门
python·数据分析·numpy
weixin_513449963 小时前
walk_these_ways项目学习记录第七篇(通过行为多样性 (MoB) 实现地形泛化)--核心环境下
人工智能·python·学习
南 阳3 小时前
Python从入门到精通day64
开发语言·python
yaaakaaang3 小时前
十二、代理模式
java·代理模式