Java中Map的排序
来源:互联网 发布:阿里云备案拍照深圳 编辑:程序博客网 时间:2024/05/29 08:30
个人认为主要还是注意ArrayList( Collection c) 这个构造方法,然后对这个List排序即可!
public static void main(String[] args) {Map map = new HashMap();map.put("First", 20);map.put("Second", 10);map.put("Third", 30); List arrayList = new ArrayList(map.entrySet());//注意构造函数 //排序前for(Iterator it = arrayList.iterator();it.hasNext();){Map.Entry entry = (Map.Entry)it.next();System.out.print(entry.getKey()+":"+entry.getValue()+" ");}Collections.sort(arrayList, new TariffComparator.TariffMapComparator());System.out.println();//排序后for(Iterator it = arrayList.iterator();it.hasNext();){Map.Entry entry = (Map.Entry)it.next();System.out.println(entry.getKey()+":"+entry.getValue());}}
排序方法:
public class TariffComparator {public static class TariffMapComparator implements Comparator{public int compare(Object o1, Object o2) {Map.Entry obj1 = (Map.Entry)o1;Map.Entry obj2 = (Map.Entry)o2;return obj1.getValue().toString().compareTo(obj2.getValue().toString());}}}
结果:
List dateList = new ArrayList(dateMap.entrySet());Collections.sort(dateList, new EmailComparator.MapComparator());public static class ComparatorByKey implements Comparator{public int compare(Object o1, Object o2) {Map.Entry m1 = (Map.Entry)o1;Map.Entry m2 = (Map.Entry)o2;Integer i1 = (Integer)m1.getKey();Integer i2 = (Integer)m2.getKey();return i1.compareTo(i2);}}
法二:
很少有人会直接使用TreeMap,为什么,当你在TreeMap结构中“put”或“remove”元素时,因为需要排序从而需要一些开销,这会影响到程序的性能,一般是我们先使用HashMap组织好数据,当需要使用关键字排序的时候,再把HashMap作为参数传入.
Map treeMap = new TreeMap(Map m).
TreeMap是一个基本红黑树的实现,它会排序他的key.
...