您的位置:首页 > 编程语言 > Java开发

java---如何实现对Map系列排序

2017-01-15 17:12 417 查看
package L15.JiHe;

import org.junit.Test;

import java.util.*;

/**
* Created by fangjiejie on 2017/3/12.
*/
public class MapSort {

@Test
public void sortmap(){
Hashtable<Integer,String> h1=new Hashtable<>();
h1.put(1,"a");
h1.put(5,"e");
h1.put(3,"c");
h1.put(2,"b");
h1.put(4,"d");
List<Map.Entry<Integer,String>> l1=new ArrayList<Map.Entry<Integer, String>>(h1.entrySet());
//ArrayList下有一个构造方法可以接收Collection类型,而h1.entrySet首先将Map系列转化为Set系列,
// Set系列是Collection的继承类,根据多态特性,作为ArrayList的形参被包装到List中
Collections.sort(l1, new Comparator<Map.Entry<Integer, String>>() {
@Override
public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
//Collections类下有一个静态方法sort,通过类名而被调用,该方法某个结构是,它有两个形参,
// 第一个是List类型(这也就是为什么要把hashtable包装到list的原因),第二个是Comparator比较器)
//这里通过匿名内部类实例化接口,并按照键值升序排序

Iterator<Map.Entry<Integer,String>> it=l1.iterator();
//因为我们将hashtable包装到List中进行了排序,所以此处对List对象进行迭代遍历
while(it.hasNext()){
Map.Entry<Integer,String> tmp=it.next();
System.out.println(tmp.getKey()+"--------"+tmp.getValue());
}
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息