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());  
相关推荐
大翻哥哥21 小时前
Python 2025:量化金融与智能交易的新纪元
开发语言·python·金融
汇能感知1 天前
摄像头模块在运动相机中的特殊应用
经验分享·笔记·科技
阿巴Jun1 天前
【数学】线性代数知识点总结
笔记·线性代数·矩阵
zhousenshan1 天前
Python爬虫常用框架
开发语言·爬虫·python
茯苓gao1 天前
STM32G4 速度环开环,电流环闭环 IF模式建模
笔记·stm32·单片机·嵌入式硬件·学习
是誰萆微了承諾1 天前
【golang学习笔记 gin 】1.2 redis 的使用
笔记·学习·golang
IMER SIMPLE1 天前
人工智能-python-深度学习-经典神经网络AlexNet
人工智能·python·深度学习
CodeCraft Studio1 天前
国产化Word处理组件Spire.DOC教程:使用 Python 将 Markdown 转换为 HTML 的详细教程
python·html·word·markdown·国产化·spire.doc·文档格式转换
皮皮林5511 天前
SpringBoot 全局/局部双模式 Gzip 压缩实战:14MB GeoJSON 秒变 3MB
java·spring boot
weixin_456904271 天前
Spring Boot 用户管理系统
java·spring boot·后端