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());  
相关推荐
fsnine5 分钟前
Python图形化界面——pyqt5教程
开发语言·python·qt
虫小宝5 分钟前
Java分布式架构下的电商返利APP技术选型与架构设计实践
java·分布式·架构
007php0079 分钟前
百度面试题解析:Zookeeper、ArrayList、生产者消费者模型及多线程(二)
java·分布式·zookeeper·云原生·职场和发展·eureka·java-zookeeper
optimistic_chen14 分钟前
【Java EE进阶 --- SpringBoot】Mybatis - plus 操作数据库
数据库·spring boot·笔记·java-ee·mybatis·mybatis-plus
凉、介33 分钟前
ARM 总线技术 —— AMBA 入门
arm开发·笔记·学习
4Forsee37 分钟前
【Android】浅析 Android 的 IPC 跨进程通信机制
android·java
扶尔魔ocy44 分钟前
python程序打包成win的exe应用(以OCR应用为例)
python·ocr·中文识别
日更嵌入式的打工仔44 分钟前
嵌入式入门:APP+BSP+HAL 三层分级架构浅析
笔记·单片机·嵌入式硬件·学习
来旺1 小时前
互联网大厂Java面试全解析及三轮问答专项
java·数据库·spring boot·安全·缓存·微服务·面试
Json____1 小时前
使用node Express 框架框架开发一个前后端分离的二手交易平台项目。
java·前端·express