`

对Map排序

 
阅读更多

本来来自:http://blog.sina.com.cn/s/blog_93daad41010119di.html

本节实例介绍对Map中的记录根据键进行排序,Map对象的键是Integer类型,排序结果可以是升序也可以是降序。

关键技术剖析:

l  只有TreeMap能够把保持的记录根据键排序,因此,可以把其他Map转换成TreeMap,转换的方法是把Map对象当做参数构造TreeMap

l  TreeMap默认用升序排序,可以指定排序用的比较器。比较实现Comparator

import java.util.Comparator;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Map.Entry;

import java.util.TreeMap;

 

public class SortMap1 {

   // 输出map

   private static void output(Map map) {

      // 第一种方法用 map.entrySet()遍历

      Iterator it = map.entrySet().iterator();

      while (it.hasNext()) {

         Map.Entry<Integer, String> s = (Entry<Integer, String>) it.next();

         int key = s.getKey();

         String value = s.getValue();

         // System.out.println("map的键是:"+key+",值是:"+value);

      }

 

      // 第二种方法用map.keySet()遍历

      it = map.keySet().iterator();

      while (it.hasNext()) {

         int key = (Integer) it.next();

         String value = (String) map.get(key);

         System.out.println("map的键是:" + key + ",值是:" + value);

 

      }

 

   }

 

   public static void main(String[] args) {

      Map map = new HashMap();

      map.put(new Integer(5), "aaa");

      map.put(new Integer(8), "bbb");

      map.put(new Integer(4), "ccc");

      map.put(new Integer(7), "ddd");

      map.put(new Integer(3), "eee");

      map.put(new Integer(1), "fff");

      System.out.println("初始化后的map:");

      output(map);

  

      // 借助TreeMap的排序功能给mayMap排序

      Map treeMap = new TreeMap(map);

      System.out.println("排序后的map:");

      output(treeMap);

  

      // 用自定义的比较器排序

      TreeMap newTreeMap = new TreeMap(new MyComparator());

      newTreeMap.putAll(map);

      System.out.println("用自定义的比较器排序后的map:");

      output(newTreeMap);

   }

}

 //比较器

class MyComparator implements Comparator {

 

   @Override

   public int compare(Object o1, Object o2) {

      int i1 = (Integer) o1;

      int i2 = (Integer) o2;

      if (i1 > i2) {

         return -1;

      }

      if (i1 < i2) {

         return 1;

      }

      return 0;

   }

}
 
 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics