Java 按值对 HashMap 进行排序 [英] Java sort HashMap by value

查看:32
本文介绍了Java 按值对 HashMap 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 HashMap:

I have this HashMap:

HashMap<String, Integer> m

它基本上存储任何单词(字符串)及其频率(整数).以下代码按值对 HashMap 进行排序:

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

如何按照与 sortByValue 相同的方法按值对这个 HashMap 进行排序?

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

推荐答案

你必须像这样创建一个自定义比较器:

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

这篇关于Java 按值对 HashMap 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆