哈希表的值排序
package weekNumber8;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class HashMapTest {
public static void main(String[] args) {
//创建一个哈希表
Map<String, Integer> map = new HashMap<String, Integer>();
//为哈希表加入键值对
map.put("f", 1);
map.put("a", 7);
map.put("b", 9);
map.put("e", 5);
hashMapSort(map);
}
public static void hashMapSort(Map map) {
//创建一个容器,将哈希表内的Entry数组对象放入list中
List<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
//通过重写比较器,对list集合进行排序
Collections.sort(list,new Comparator<Map.Entry<String,Integer>>() {
//升序排序
public int compare(Entry<String, Integer> o1,Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
//遍历排序后的list集合
for(Entry<String, Integer> mapp:list){
System.out.println(mapp.getKey()+":"+mapp.getValue());
}
}
}