【问题标题】:Get Value from Key, Value is a List从键中获取值,值是一个列表
【发布时间】:2015-10-03 15:19:26
【问题描述】:

如何从我的 Value 中获取 Key?

我的哈希图:

public static final Map<String, List<String>> Server = new HashMap<>();

我的尝试:

  public static Object getKeyFromValue(String value) {
        for (Object o : Server.keySet()) {
             if (Server.get(o).equals(value)) {
                 return o;
             }
         }
         return null;
   }

它不起作用,因为值是一个列表。

【问题讨论】:

  • 所以如果我理解正确你想返回存储在特定键下的列表?或者你想要完成什么?

标签: java list hashmap


【解决方案1】:

使用List#contains:

if (Server.get(o).contains(value)) {
    //...
}

【讨论】:

    【解决方案2】:

    当您迭代 Map 时,如果您需要键和值,最好迭代 entrySet 而不是 keySet

    public static String getKeyFromValue(String value) {
        for (Map.Entry<String, List<String>> e : Server.entrySet()) {
            if (e.getValue().contains(value)) {
                return e.getKey();
            }
        }
        return null;
    }
    

    这应该可行,但我不喜欢它的 3 件事(除了Server 以大写字母开头)。

    1. 对于许多List 实现(包括ArrayListLinkedList),contains 很慢,因为它是线性搜索。改用HashSet 可能会更好。
    2. 如果value 出现在映射中的多个列表中,则返回的键可以是多个答案中的任何一个。最好用方法名来表明这一点(例如getAnyKeyForValue)。
    3. 最好返回Optional&lt;String&gt;,而不是使用null 表示未找到该值。

    考虑到所有这些点并利用并行性的 Java 8 解决方案将是

    public static Optional<String> getAnyKeyForValue(String value) {
        return Server.entrySet()
                     .parallelStream()
                     .filter(e->e.getValue().contains(value))
                     .map(Map.Entry::getKey)
                     .findAny();
    }
    

    【讨论】:

      【解决方案3】:

      只需从 equals 更改为 contains 即可。一切都保持不变

      public static Object getKeyFromValue(String value) {
          for (Object o : Server.keySet()) {
              if (Server.get(o).contains(value)) {
                   return o;
               }
           }
           return null;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-17
        • 1970-01-01
        • 2015-09-05
        • 2012-01-19
        相关资源
        最近更新 更多