ITeye博客

Map 排序

grefr · 2013-08-14 17:32 · 算法 · 编程语言 · Markdown

详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcytp42

Map的排序常分为两种情况,1、按key值排序;2、按value排序

1.我们先讨论按key值进行排序

我们先看一下这个Sorter类:

public static Map sort(Map map) {
     Map mapVK = new TreeMap(
         new Comparator() {
             public int compare(Object obj1, Object obj2) {
                 String v1 = (String)obj1;
                 String v2 = (String)obj2;
                 int s = v2.compareTo(v1);
                 return s;
             }
         }
     );
    Set col = map.keySet();
     Iterator iter = col.iterator();
     while (iter.hasNext()) {
         String key = (String) iter.next();
         Integer value = (Integer) map.get(key);
         mapVK.put(key, value);
     }
     return mapVK;
 }

}

public class SortHashMap {

}
public static void main(String args) {
     Map maps = new HashMap();
     maps.put("boy", 8);
     maps.put("cat", 7);
     maps.put("dog", 1);
     maps.put("apple", 5);
     //排序前的输出
     Set set = maps.entrySet();
     Iterator i = set.iterator();
     while(i.hasNext()){
         Map.Entry entry1=(Map.Entry)i.next();
         System.out.println(entry1.getKey() + "-------->" + entry1.getValue());
     }
    System.out.println("----------------");
      //排序后的输出
     Map sortMaps = Sorter.sort(maps);
     Set sortSet = sortMaps.entrySet();
     Iterator ii = sortSet.iterator();
     while(ii.hasNext()){
         Map.Entry entry1=(Map.Entry)ii.next();
         System.out.println(entry1.getKey() + "-------->" + entry1.getValue());
     }
     
 }

}

cat-------->7 apple-------->5 dog-------->1 boy-------->8

dog-------->1 cat-------->7 boy-------->8 apple-------->5 经过排序后的Map有序了,是按照字母的逆序排列的。

还是上面的那个例子,我们想要按照各类对象的数量打印出类别的名称。 我们再来修改一下这个SortHashMap类:

public SortHashMap() {

public static void main(String args) {
     Map maps = new HashMap();
     maps.put("boy", 8);
     maps.put("cat", 7);
     maps.put("dog", 1);
     maps.put("apple", 5);
     //排序前的输出
     Set set = maps.entrySet();
     Iterator i = set.iterator();
     while(i.hasNext()){
         Map.Entry entry1=(Map.Entry)i.next();
         System.out.println(entry1.getKey() + "-------->" + entry1.getValue());
     }
    System.out.println("----------------");
     //排序后的输出
  List> info = new ArrayList>(maps.entrySet());
     Collections.sort(info, new Comparator>() {
         public int compare(Map.Entry obj1, Map.Entry obj2) {
             return obj2.getValue() - obj1.getValue();
         }
     });
    for (int j = 0; j" + info.get(j).getValue());
     }
 }

}

cat-------->7 apple-------->5 dog-------->1 boy-------->8

boy------->8 cat------->7 apple------->5 dog------->1

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。