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());  
相关推荐
yuxb736 分钟前
Zabbix企业级分布式监控系统(上)
笔记·学习·zabbix
元亓亓亓8 分钟前
Leet热题100--208. 实现 Trie (前缀树)--中等
java·开发语言
现在,此刻9 分钟前
李沐深度学习笔记D1-什么是深度学习
人工智能·笔记·深度学习
拿破轮11 分钟前
不小心在idea中点了add 到版本控制 怎么样恢复?
java·ide·intellij-idea
星空的资源小屋1 小时前
Text Grab,一款OCR 截图文字识别工具
python·django·ocr·scikit-learn
寒秋丶1 小时前
Milvus:Json字段详解(十)
数据库·人工智能·python·ai·milvus·向量数据库·rag
猿来是你_L2 小时前
UGUI笔记——3D坐标转换成UGUI坐标
笔记·3d
自由随风飘5 小时前
python 题目练习1~5
开发语言·python
cynicme6 小时前
力扣3318——计算子数组的 x-sum I(偷懒版)
java·算法·leetcode
青云交7 小时前
Java 大视界 -- Java 大数据在智能教育学习效果评估与教学质量改进实战
java·实时分析·生成式 ai·个性化教学·智能教育·学习效果评估·教学质量改进