zoukankan      html  css  js  c++  java
  • HashMap和TreeMap的常用排序方法

    一、简单描述

    Map是键值对的集合接口,它的实现类主要包括:HashMap,TreeMap,HashTable以及LinkedHashMap等。

    TreeMap:能够把它保存的记录根据键(key)排序,默认是按升序排序,也可以指定排序的比较器,该映射根据其键的自然顺序进行排序,或者根据创建映射时提供的 Comparator 进行排序,具体取决于使用的构造方法。

    HashMap的值是没有顺序的,它是按照key的HashCode来实现的,根据键可以直接获取它的值,具有很快的访问速度。HashMap最多只允许一条记录的键为Null(多条会覆盖);允许多条记录的值为 Null。非同步的。

     

    TreeMap默认是升序的,如果我们需要改变排序方式,则需要使用比较器:Comparator。

            
            Map< Integer, String> map=new TreeMap<>(new Comparator<Integer>() {
                
                @Override
                public int compare(Integer o1, Integer o2) {
    //                return o1.compareTo(o2);       //按照key值大小升序排列       -o1.compareTo(o2)即o2.compareTo(o1)按照key值大小降序排列
                    return -1;                     //按put反顺序排序      1则为 put顺序排列
                }
            });
            map.put(5, "a");
            map.put(3, "c");
            map.put(4, "b");
            map.put(2, "d");
            map.put(1, "e");
            for(Entry<Integer, String> aEntry:map.entrySet()) {
                System.out.println(aEntry.getKey()+":"+aEntry.getValue());
            }
        

    如果想通过key值排序  则需要通过List解决

    Map< Integer, String> map=new TreeMap<>();
            map.put(5, "a");
            map.put(3, "c");
            map.put(4, "b");
            map.put(2, "d");
            map.put(1, "e");
            List<Entry<Integer,String>> list =new ArrayList<Entry<Integer,String>>(map.entrySet());
            Collections.sort(list, new Comparator<Entry<Integer, String>>() {
    
                @Override
                public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {
                    // TODO Auto-generated method stub
                    return o1.getValue().compareTo(o2.getValue());
                }
            });
            for(Entry<Integer, String> aEntry:list) {
                System.out.println(aEntry.getKey()+":"+aEntry.getValue());
            }

    运行结果为:

    5:a
    4:b
    3:c
    2:d
    1:e

    对于HashMap来说  没法使用比较器:Comparator  则可以用TreeMap的第二种方法  代码一样

    最后友情提示一点:

    有时候代码没问题 list老是报错(The type List is not generic; it cannot be parameterized with arguments )

    则是自动导入了import java.awt.List;而不是import java.util.List;

  • 相关阅读:
    2006年百度之星程序设计大赛试题初赛题目题4剪刀石头布
    2006年百度之星程序设计大赛试题初赛题目题5座位调整
    Linux2.6用户空间堆栈区的分配与回收
    Linux2.6物理内存管理
    2006年百度之星程序设计大赛试题初赛题目题6百度语言翻译机
    带权的二分匹配
    二分图带权匹配KuhnMunkres算法(有修改)
    Linux2.6虚拟内存管理
    Linux2.6为数据结构分配内存slab
    2012225面试题目
  • 原文地址:https://www.cnblogs.com/qiangqiangqiang/p/7879380.html
Copyright © 2011-2022 走看看