Java sort HashMap by value [duplicate]

对着背影说爱祢 提交于 2019-12-18 11:47:29

问题


I have this HashMap:

HashMap<String, Integer> m

which basically stores any word (String) and its frequency (integer). The following code is ordering the HashMap by value:

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

Now the scenario has changed and i have this:

HashMap<String, doc>;

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

How can i sort this HashMap by value, following the same approach as sortByValue?


回答1:


You have to create a custom comparator like this:

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 instead of

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

why not write like (this of course checking null and empty string)

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


来源:https://stackoverflow.com/questions/7965132/java-sort-hashmap-by-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!