对Map排序

来源:互联网 发布:绝对值编码器编程实例 编辑:程序博客网 时间:2024/06/14 23:15

     本节实例介绍对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;

  }

}

0 0
原创粉丝点击