【问题标题】:How to get the specific <K,V> entry based on the given key in Java HashMap?如何根据 Java HashMap 中的给定键获取特定的 <K,V> 条目?
【发布时间】:2021-06-05 20:34:42
【问题描述】:

例如。我有以下HashMap,如果我知道密钥'b',如何获取条目'b'=6。有什么办法吗?

Map<Character, Integer> map=new HashMap<>();
map.put('a',7);
map.put('b',6);
map.put('c',5);`

顺便说一句,我想这样做是因为所有这些条目都在优先级队列中。我必须从优先级队列中删除该条目并重新插入以确保它是有序的。

谢谢。

【问题讨论】:

  • 我不明白。为什么一个简单的get() 电话不够用?例如。 Character key = 'b'; Integer value = map.get(key);
  • 为什么要把k+v存入优先队列?最好只存储密钥。

标签: java dictionary hashmap


【解决方案1】:

如果您知道密钥,只需使用Map#get(Object) 获取值。只要你知道两者,你就有了entryMap 接口没有提供返回某个条目的特定方法。

Map<Character, Integer> map = ...
Character key = 'b';
Integer value = map.get(key);

// now with the 'key' and 'value' that make TOGETHER an entry.

如果你真的需要 Entry&lt;Character, Integer&gt; 像这样构造它:

Map.Entry<Character, Integer> entry = new SimpleEntry<>(key, value);

没有更好的方法。有人会说您可以使用 Stream API 遍历条目并返回找到的第一个条目,但是,您失去了 HashMap 的主要好处,即恒定时间查找。

// DON'T DO THIS!

Entry<Character, Integer> entry = map.entrySet().stream()
        .filter(e -> key.equals(e.getKey()))
        .findFirst()
        .orElse(null);

【讨论】:

    【解决方案2】:

    你可以这样做

    public Entry<Character, Integer> entry_return(Map<Character, Integer> map) {
        for(Map.Entry<Character, Integer> entry : map.entrySet()) {
            if(entry.getKey() == 'b')
                return entry;
        }
    }
    

    如果您确实需要该条目,或者使用流 API,但我不知道这是否非常常见/有用

    【讨论】:

    • 重要的是要指出 HashMap 的主要好处丢失了。
    【解决方案3】:

    从 Java 9 开始,您可以使用静态方法 Map.entry​(K k, V v),其中:

    返回包含给定键和值的不可修改的Map.Entry

    因此,您可以获得Entry&lt;K, V&gt; 实例,如下所示:

    Map.Entry<Character, Integer> entry = Map.entry(key, map.get(key));
    

    其中map 存储对您的Map&lt;K, V&gt; 实例的引用。

    【讨论】:

      猜你喜欢
      • 2022-08-15
      • 2021-09-21
      • 2018-10-10
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 2014-12-03
      相关资源
      最近更新 更多