当前位置:网站首页 > 技术博客 > 正文

java map集合排序



Java TreeMap

可以按照

value 排序

,可以通过

实现

Comparator接口来

实现

。具体步骤如下:

1. 创建一个

实现

Comparator接口的类,重写compare方法,比较两个

value

的大小。

2. 创建一个

TreeMap

对象,并将

实现

了Comparator接口的类作为参数传入。

3. 将需要

排序

的

键 值

对添加到

TreeMap

中。

4. 使用entrySet()方法获取

TreeMap

中的所有

键 值

对,并将其转换为List。

5. 使用Collections.sort()方法对List进行

排序

。

6. 遍历

排序

后的List,输出

键 值

对。

示例代码如下:

 import java .util.*;  public class TreeMap SortBy Value { public static void main(String[] args) { // 创建一个 实现 Comparator接口的类  Value Comparator vc = new Value Comparator(); // 创建一个 TreeMap 对象,并将 实现 了Comparator接口的类作为参数传入  TreeMap <String, Integer> map = new TreeMap <>(vc); // 将需要 排序 的 键 值 对添加到 TreeMap 中 map.put("apple", 10); map.put("banana", 5); map.put("orange", 8); // 使用entrySet()方法获取 TreeMap 中的所有 键 值 对,并将其转换为List List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet()); // 使用Collections.sort()方法对List进行 排序 Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o1.get Value ().compareTo(o2.get Value ()); } }); // 遍历 排序 后的List,输出 键 值 对 for (Map.Entry<String, Integer> entry : list) { System.out.println(entry.get Key () + " : " + entry.get Value ()); } } }  // 实现 Comparator接口的类 class Value Comparator implements Comparator<String> { Map<String, Integer> map = new HashMap<>(); public Value Comparator() {} public Value Comparator(Map<String, Integer> map) { this.map.putAll(map); } @Override public int compare(String s1, String s2) { if (map.get(s1) >= map.get(s2)) { return 1; } else { return -1; } } } 

  • 上一篇: stream.of方法
  • 下一篇: yml文件格式要求
  • 版权声明:


    相关文章:

  • stream.of方法2024-12-10 08:01:05
  • 破解手机锁屏密码的方法是什么?2024-12-10 08:01:05
  • 梯度提升树分类算法2024-12-10 08:01:05
  • python爬虫爬取网页所有数据2024-12-10 08:01:05
  • 极大似然算法2024-12-10 08:01:05
  • yml文件格式要求2024-12-10 08:01:05
  • 单片机c语言编程入门2024-12-10 08:01:05
  • date函数举例2024-12-10 08:01:05
  • makefile error32024-12-10 08:01:05
  • 线程同步方法有几种2024-12-10 08:01:05