Java 按值对哈希映射进行排序

2022-09-02 04:47:58

我有这个哈希地图:

HashMap<String, Integer> m

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

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>;
}

我如何按值对此HashMap进行排序,遵循与sortByValue相同的方法?


答案 1

您必须创建一个自定义比较器,如下所示:

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 + " ");
  }
}

答案 2

@jackturky而不是

public int compare(String s1, String s2) {
    int c = s2.length() - s1.length();
    if (c == 0)
      c = s1.compareToIgnoreCase(s2);
    return c;
  }

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

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

推荐