按值对 HashMap 进行排序

发布于 2025-01-03 05:42:04 字数 272 浏览 1 评论 0原文

当我需要按值对 HashMap 进行排序时,建议似乎是创建 HashMap,然后将数据放入按值排序的 TreeMap 中。

例如:对映射进行排序<键,值> ;按值(Java)

我的问题:为什么有必要这样做?为什么不创建一个 TreeMap(按键排序),然后按值对其进行排序?

When I need to sort a HashMap by value, the advice seems to be to create the HashMap and then put the data into a TreeMap which is sorted by value.

For example: Sort a Map<Key, Value> by values (Java)

My question: why is it necessary to do this? Why not create a TreeMap(which is sorted by keys) and then sort it in place by value?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

寄与心 2025-01-10 05:42:04

如果您知道自己的值是唯一的,则可以使用 Guava 的 BiMap(双向地图)来存储数据。像创建 HashMap 一样创建一个 HashBiMap,然后从其逆向创建一个新的 TreeMap

new TreeMap<>(biMap.inverse());

然后该映射将按值排序。请记住,您所认为的“键”和“值”将会被交换。

如果您的值不唯一,您可以创建逆多重映射。多重映射本质上是从每个键到一个或多个值的映射。它通常是通过制作从键到列表的映射来实现的。但你不必这样做,因为谷歌已经为你做了。只需从现有地图创建一个多重地图,然后让 Guava 为您将其反转为 TreeMultimap,正如您所猜测的,它是一个可以容纳多个值的 TreeMap每个键。

Multimaps.invertFrom(Multimaps.forMap(myMap), new TreeMultimap<V, K>());

提供了 Multimap 文档。

If you know your values to be unique, you can use Guava's BiMap (bidirectional map) to store the data. Create a HashBiMap as you would your HashMap, then create a new TreeMap from its inverse:

new TreeMap<>(biMap.inverse());

That map will then be sorted by the values. Remember that what you're thinking of as "keys" and "values" will be swapped.

If your values are not unique, you can create a multimap of the inverse. A multimap is essentially a mapping from each key to one or more values. It's usually implemented by making a map from a key to a list. You don't have to do that though, because Google did it for you. Just create a multimap from your existing map, and ask Guava to invert it for you into a TreeMultimap, which, as you can guess, is a TreeMap that can hold multiple values per key.

Multimaps.invertFrom(Multimaps.forMap(myMap), new TreeMultimap<V, K>());

Multimap documentation is provided.

燕归巢 2025-01-10 05:42:04

因为您无法手动重新排序 TreeMap 的条目。 TreeMap 条目总是按键排序。

我要扔掉 地图可以按照值的顺序迭代作为“如何做”的另一个答案,但是......具体来说,一个不返回令人窒息的地图的解决方案(通过抛出例外)对不在原始映射中的键进行查询。

Because you can't reorder the entries of a TreeMap manually. TreeMap entries are always sorted on the keys.

I'm going to throw out Map that could be iterated in the order of values as another answer to "How to do it," though...specifically, a solution which doesn't return a map that chokes (by throwing exceptions) on queries to keys not in your original map.

归途 2025-01-10 05:42:04

我有这个非常小的代码,运行良好:

public class SortMapByValues {
    public static void main(String[] args) {

        Map<Integer, String> myMap = new LinkedHashMap<Integer, String>();

        myMap.put(100, "hundread");
        myMap.put(500, "fivehundread");
        myMap.put(250, "twofifty");
        myMap.put(300, "threehundread");
        myMap.put(350, "threefifty");
        myMap.put(400, "fourhundread");

        myMap = sortMapByValues(myMap);

        for (Map.Entry<Integer, String> entry : myMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

    }

    public static Map<Integer, String> sortMapByValues(
            Map<Integer, String> firstMap) {
        Map<String, Integer> SecondyMap = new TreeMap<String, Integer>();

        for (Map.Entry<Integer, String> entry : firstMap.entrySet()) {
            SecondyMap.put(entry.getValue(), entry.getKey());
        }
        firstMap.clear();
        for (Map.Entry<String, Integer> entry : SecondyMap.entrySet()) {
            firstMap.put(entry.getValue(), entry.getKey());
        }
        return firstMap;
    }

}

输出:

500 fivehundread  
400 fourhundread  
100 hundread  
350 threefifty  
300 threehundread  
250 twofifty 

I have this very small code which is working fine:

public class SortMapByValues {
    public static void main(String[] args) {

        Map<Integer, String> myMap = new LinkedHashMap<Integer, String>();

        myMap.put(100, "hundread");
        myMap.put(500, "fivehundread");
        myMap.put(250, "twofifty");
        myMap.put(300, "threehundread");
        myMap.put(350, "threefifty");
        myMap.put(400, "fourhundread");

        myMap = sortMapByValues(myMap);

        for (Map.Entry<Integer, String> entry : myMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

    }

    public static Map<Integer, String> sortMapByValues(
            Map<Integer, String> firstMap) {
        Map<String, Integer> SecondyMap = new TreeMap<String, Integer>();

        for (Map.Entry<Integer, String> entry : firstMap.entrySet()) {
            SecondyMap.put(entry.getValue(), entry.getKey());
        }
        firstMap.clear();
        for (Map.Entry<String, Integer> entry : SecondyMap.entrySet()) {
            firstMap.put(entry.getValue(), entry.getKey());
        }
        return firstMap;
    }

}

Output:

500 fivehundread  
400 fourhundread  
100 hundread  
350 threefifty  
300 threehundread  
250 twofifty 
海未深 2025-01-10 05:42:04

我使用 Java 8 Stream API 编写了以下单行代码,以按值对任何给定映射进行排序:

List<Map.Entry<String, String>> sortedEntries = map.entrySet().stream()
  .sorted((o1, o2) -> o1.getValue().compareTo(o2.getValue())).collect(Collectors.toList());

I wrote the following one-liner using Java 8 Stream API to sort any given map by value:

List<Map.Entry<String, String>> sortedEntries = map.entrySet().stream()
  .sorted((o1, o2) -> o1.getValue().compareTo(o2.getValue())).collect(Collectors.toList());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文