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());  
相关推荐
2401_cf2 小时前
为什么hadoop不用Java的序列化?
java·hadoop·eclipse
帮帮志2 小时前
idea整合maven环境配置
java·maven·intellij-idea
LuckyTHP2 小时前
java 使用zxing生成条形码(可自定义文字位置、边框样式)
java·开发语言·python
mahuifa4 小时前
(7)python开发经验
python·qt·pyside6·开发经验
无声旅者5 小时前
深度解析 IDEA 集成 Continue 插件:提升开发效率的全流程指南
java·ide·ai·intellij-idea·ai编程·continue·openapi
学地理的小胖砸5 小时前
【Python 操作 MySQL 数据库】
数据库·python·mysql
安迪小宝5 小时前
6 任务路由与负载均衡
运维·python·celery
Blossom.1185 小时前
使用Python实现简单的人工智能聊天机器人
开发语言·人工智能·python·低代码·数据挖掘·机器人·云计算
Ryan-Joee5 小时前
Spring Boot三层架构设计模式
java·spring boot
lisw055 小时前
Python高级进阶:Vim与Vi使用指南
python·vim·excel