简体   繁体   English

如何根据 Java 中的值从 HashMap 返回键

[英]How to return a Key from HashMap based on its Value in Java

Consider the following:考虑以下:

for (Boolean i: x.values()) {
    if (i == false) {
        return // KEY;
    }
}

In the above code, I am trying to iterate through the HashMap .在上面的代码中,我试图遍历HashMap And I want to return a Key when the value is false .当值为false时,我想返回一个Key

How can I do it?我该怎么做?

You need to loop through the HashMap's entrySet :您需要遍历 HashMap 的entrySet

for (Map.Entry<Object, Boolean> entry : x.entrySet()) {
   if(entry.getValue() == false){
        return entry.getKey();
    }
}

In order to find first a key that is mapped to a particular value you need to iterate either over the key set or over the entry set .为了首先找到映射到特定值的键,您需要遍历键集条目集

The latter option is preferred because at each iteration step you will have a key-value pair on your hands.后一种选择是首选,因为在每个迭代步骤中,您手头都会有一个键值对 Therefore, it would be slightly faster than interrogating the map at every iteration ( remainder: there could be collisions in a real hashmap, and finding the target node can take more time than accessing the value on a map-entry ).因此,它会比在每次迭代中查询映射稍微快一些(余数:在真正的哈希映射中可能存在冲突,并且找到目标节点可能比访问映射条目上的值花费更多时间)。

But you definitely can't use a collection of map values returned by a method values() like you're doing in the code-snippet you've posted.但是您绝对不能像在您发布的代码片段中那样使用由方法values()返回的地图值集合。 There's no fast way of retrieving a key when you have only a value on your hands.当您手头只有一个时,没有快速检索密钥的方法。

In the example below, ill show how to obtain a key from a map of arbitrary type that matches the condition (a Predicate ) provided dynamically at runtime using Stream API .在下面的示例中,将展示如何从与在运行时使用Stream API动态提供的条件( Predicate )匹配的任意类型的映射中获取

There's one important thing to consider: target value might not be present in the map.有一件重要的事情需要考虑:目标值可能不会出现在地图中。 And the code should handle this case.并且代码应该处理这种情况。 We can provide a default value (either directly or via Supplier ), throw an exception (if according to the application logic the given value is always expected to be present), or by utilizing methods ifPresent() , ifPresentOrElse() provided by the Optional class.我们可以提供一个默认值(直接或通过Supplier ),抛出一个异常(如果根据应用程序逻辑,给定的值总是存在的),或者通过使用Optional提供的ifPresent()ifPresentOrElse()方法班级。 In the example below, I've chosen to provide a default value.在下面的示例中,我选择提供默认值。

Take a look at these tutorials for more information on lambda expressions and streams查看这些教程以获取有关lambda 表达式的更多信息

public static void main(String[] args) {
    Map<String, Boolean> sourceMap =
        Map.of("A", true, "B", false, "C", true);
    
    String result = getFirstKey(sourceMap, entry -> !entry.getValue(), "");
    System.out.println(result);
}

public static <K, V> K getFirstKey(Map<K, V> map,
                                   Predicate<Map.Entry<K, V>> condition,
                                   K defaultKey) {
    
    return map.entrySet().stream()
        .filter(condition)         // Stream<Map.Entry<K, V>>
        .findFirst()               // Optional<Map.Entry<K, V>>
        .map(Map.Entry::getKey)    // Optional<K>
        .orElse(defaultKey); // or apply .orElseThrow() depending on your needs
}

Output输出

B // key assosiated with a value of `false`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM