根据Java中的值对地图进行排序的最简单方法是什么? [英] What is the easiest way to sort maps according to values in Java?

查看:196
本文介绍了根据Java中的值对地图进行排序的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的哈希值根据值按降序排序。我如何用Java做到这一点?

I want my hash to sort in descending order according to the values. How do I do that in Java?

推荐答案

A HashMap (及其遗留的前身 Hashtable )本质上是无序的。即使你对它进行排序,它仍将是无序的。如果要维护广告订单,请使用 LinkedHashMap 。如果您想对进行自动排序,无论插入顺序如何,请使用 SortedMap

A HashMap (and its legacy predecesor Hashtable) is by nature unordered. Even if you sort it, it will remain unordered. If you want to maintain insertion order, then use LinkedHashMap instead. If you want an automatic sort on keys, regardless of insertion order, then use SortedMap instead.

如果要排序上的 Map ,那么您基本上需要将键/值对放在另一种可排序的数据结构中,例如列出<条目< K< K>> ,然后使用集合#sort()对其进行排序 Compatator< Entry< K< K>> ,最后用它重新填充 LinkedHashMap (不是 HashMap 或者你将再次失去订购。)

If you want to sort a Map on values, then you basically need to put the key/value pairs in another kind of a sortable data structure, e.g. List<Entry<K, V>>, then sort it using Collections#sort() with help of a Compatator<Entry<K, V>> and finally repopulate a LinkedHashMap with it (not a HashMap or you will lose the ordering again).

这是一个基本的例子(抛开明显的运行时异常处理):

Here's a basic example (leaving obvious runtime exception handling aside):

// Prepare.
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "bar");
map.put("bar", "waa");
map.put("waa", "foo");
System.out.println(map); // My JVM shows {waa=foo, foo=bar, bar=waa}

// Get entries and sort them.
List<Entry<String, String>> entries = new ArrayList<Entry<String, String>>(map.entrySet());
Collections.sort(entries, new Comparator<Entry<String, String>>() {
    public int compare(Entry<String, String> e1, Entry<String, String> e2) {
        return e1.getValue().compareTo(e2.getValue());
    }
});

// Put entries back in an ordered map.
Map<String, String> orderedMap = new LinkedHashMap<String, String>();
for (Entry<String, String> entry : entries) {
    orderedMap.put(entry.getKey(), entry.getValue());
}

System.out.println(orderedMap); // {foo=bar, waa=foo, bar=waa}

要排序 descencing ,使用以下 Comparator 。基本上只是交换条目进行比较:

To sort it descencing, use the following Comparator. Basically just swap the entries to compare:

Collections.sort(entries, new Comparator<Entry<String, String>>() {
    public int compare(Entry<String, String> e1, Entry<String, String> e2) {
        return e2.getValue().compareTo(e1.getValue()); // Sorts descending.
    }
});

这篇关于根据Java中的值对地图进行排序的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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