# 疯狂

STANDING ON THE SHOULDERS OF GIANTS
posts - 481, comments - 486, trackbacks - 0, articles - 1
BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

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

public class Sorter {

public static Map sort(Map map) {
Map<Object, Object> mapVK = new TreeMap<Object, Object>(
new Comparator<Object>() {
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 SortHashMap() {

}

public static void main(String[] args) {
Map<String, Integer> maps = new HashMap<String, Integer>();
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<String, Integer> entry1=(Map.Entry<String, Integer>)i.next();
System.out.println(entry1.getKey() + "-------->" + entry1.getValue());
}

System.out.println("----------------");
//排序后的输出
Map<String, Integer> sortMaps = Sorter.sort(maps);
Set sortSet = sortMaps.entrySet();
Iterator ii = sortSet.iterator();
while(ii.hasNext()){
Map.Entry<String, Integer> entry1=(Map.Entry<String, Integer>)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

2、我们再讨论如何按value值进行排序。

public class SortHashMap {

public SortHashMap() {

}

public static void main(String[] args) {
Map<String, Integer> maps = new HashMap<String, Integer>();
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<String, Integer> entry1=(Map.Entry<String, Integer>)i.next();
System.out.println(entry1.getKey() + "-------->" + entry1.getValue());
}

System.out.println("----------------");
//排序后的输出
List<Map.Entry<String, Integer>> info = new ArrayList<Map.Entry<String, Integer>>(maps.entrySet());
Collections.sort(info, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> obj1, Map.Entry<String, Integer> obj2) {
return obj2.getValue() - obj1.getValue();
}
});

for (int j = 0; j<info.size();j++) {
System.out.println(info.get(j).getKey() + "------->" + info.get(j).getValue());
}
}
}

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

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

 只有注册用户登录后才能发表评论。 网站导航: 相关文章: