关于排序:按值排序Java排序图

Java sort HashMap by value

本问题已经有最佳答案,请猛点这里访问。

我有这个哈希图:

1
HashMap<String, Integer> m

它基本上存储任何单词(字符串)及其频率(整数)。以下代码按值对哈希图排序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
    }

现在场景已经改变了,我得到了:

1
2
3
4
5
6
HashMap<String, doc>;

class doc{
integer freq;
HashMap<String, Double>;
}

如何按照与SortByValue相同的方法按值对该哈希图进行排序?


您必须创建一个这样的定制比较器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
2
3
4
5
6
public int compare(String s1, String s2) {
    int c = s2.length() - s1.length();
    if (c == 0)
      c = s1.compareToIgnoreCase(s2);
    return c;
  }

为什么不写像(这当然检查空字符串)

1
2
3
public int compare(String s1, String s2) {
          return s1.compareToIgnoreCase(s2);
     }