如果是按键排序,我们可以用TreeMap;
但如果是按值排序呢?
比如要将一个文件中的单词按出现次数进行统计。
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Solution {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 10);
map.put("b", 30);
map.put("c", 50);
map.put("d", 40);
map.put("e", 20);
System.out.println(map);
TreeMap<String, Integer> sortedMap = SortByValue(map);
System.out.println(sortedMap);
}
public static TreeMap<String, Integer> SortByValue(
HashMap<String, Integer> map) {
ValueComparator vc = new ValueComparator(map);
TreeMap<String, Integer> sortedMap = new TreeMap<String, Integer>(vc);
sortedMap.putAll(map);
return sortedMap;
}
}
class ValueComparator implements Comparator<String> {
Map<String, Integer> map;
public ValueComparator(Map<String, Integer> base) {
this.map = base;
}
public int compare(String a, String b) {
if (map.get(a) >= map.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}
这种方式虽然有效,但只能用于 HashMap<String, Integer>。
第二种方式:
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Solution {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 10);
map.put("b", 30);
map.put("c", 50);
map.put("d", 40);
map.put("e", 20);
System.out.println(map);
Map sortedMap = sortByValue(map);
System.out.println(sortedMap);
}
public static Map sortByValue(Map unsortedMap) {
Map sortedMap = new TreeMap(new ValueComparator(unsortedMap));
sortedMap.putAll(unsortedMap);
return sortedMap;
}
}
class ValueComparator implements Comparator {
Map map;
public ValueComparator(Map map) {
this.map = map;
}
public int compare(Object keyA, Object keyB) {
Comparable valueA = (Comparable) map.get(keyA);
Comparable valueB = (Comparable) map.get(keyB);
return valueB.compareTo(valueA);
}
}
考虑到类型安全,这种方式是不被推荐的,但也算是提供了一种做法。
另外一种方式:
public static Map sortByValue(Map unsortMap) {
List list = new LinkedList(unsortMap.entrySet());
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
Map sortedMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
如果有其他更好的,记得分享哦;