Java - HashMap分别按Key和Value进行排序
我们都知道,Java中的Map结构是key->value键值对存储的,而且根据Map的特性,同一个Map中 不存在两个Key相同的元素,而value不存在这个限制。换句话说,在同一个Map中Key是唯一的,而value不唯一。Map是一个接口,我们不能直接声明一个Map类型的对象,在实际开发中,比较常用的Map性数据结构是HashMap和TreeMap,它们都是Map的直接子类。
如果考虑到存取效率的话,建议使用HashMap数据结构,而如果需要考虑到Key的顺序,建议使用TreeMap,但是TreeMap在删除、添加过程中需要排序,性能比较差。
1. 以Key进行排序,可以声明一个TreeMap对象
Map<Integer,Person> map = new TreeMap<Integer,Person>();
然后往map中添加元素,可以通过输出结果,可以发现map里面的元素都是按key的值排好序的。
我们也可以声明一个HashMap对象,然后把HashMap对象赋值给TreeMap,如下:
Map<Integer,Person> map = new HashMap<Integer,Person>(); TreeMap treemap = new TreeMap(map);
2. 以value进行排序,先声明一个HashMap对象,然后将Map集合转换成List集合中,最后通过Collections.sort(List l, Comparator c)方法来进行排序。
Map<String,Integer> map = new HashMap<String,Integer>(); //将Map转化成List才能按value进行排序 List<Entry<String,Integer>> list =new ArrayList<Entry<String,Integer>>(map.entrySet()); //按value创建比较器来排序 Collections.sort(list, new Comparator<Entry<String, Integer>>() { public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { return(o1.getValue() - o2.getValue()); } });
上述代码是升序排序。如果需要降序排序,只需要修改为o2.getValue() - o1.getValue()即可。