我有这个HashMap:
HashMap<String, Integer> m
基本上存储任何单词(String)及其频率(整数)。 以下代码按值排序HashMap:
public static Map<String, Integer> sortByValue(Map<String, Integer> map) {
List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> m1, Map.Entry<String, Integer> m2) {
return (m2.getValue()).compareTo(m1.getValue());
}
});
Map<String, Integer> result = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
现在情况发生了变化,我有了这个:
HashMap<String, doc>;
class doc{
integer freq;
HashMap<String, Double>;
}
我如何按照与sortByValue相同的方法按值对HashMap进行排序?
答案 0 :(得分:5)
你必须创建一个这样的自定义比较器:
import java.util.Comparator;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"};
Arrays.sort(strings, new Comparator<String>() {
public int compare(String s1, String s2) {
int c = s2.length() - s1.length();
if (c == 0)
c = s1.compareToIgnoreCase(s2);
return c;
}
});
for (String s: strings)
System.out.print(s + " ");
}
}
答案 1 :(得分:1)
@jackturky而不是
public int compare(String s1, String s2) {
int c = s2.length() - s1.length();
if (c == 0)
c = s1.compareToIgnoreCase(s2);
return c;
}
为什么不写(这当然是检查null和空字符串)
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}