简体   繁体   English

Java Hashmap - 通过在方法中传递“值”作为参数来获取/检索“键”

[英]Java Hashmap - Getting/retrieving “key” by passing “value” as parameter in a method

Both Key and value are user input. Key 和 value 都是用户输入。 Then value is passed to the as variable to retrieve the corresponding key for the value.然后将 value 传递给 as 变量以检索 value 的相应键。

My output returns NULL.我的 output 返回 NULL。 Please guide me to retrieve key by passing value.请指导我通过传递值来检索密钥。

public class DomainBO {

    private Map<String,String> domainMap;
        
    public Map<String,String> getDomainMap() {
        return domainMap;
    }

    public void setDomainMap(Map<String,String> domainMap) {
        this.domainMap = domainMap;
    }

    //This method should add the domainName as key and their ipAddress as value into a Map
    public void addDNSDetails  (String domainName,String ipAddress){    
        domainMap.put(domainName, ipAddress);       
    }
    
    /*
     * This method should return the domain name for the specific ipAddress which is passed as the argument. 
     * For example: If the map contains the key and value as:
     * www.yahoo.net    205.16.214.15
       www.gmail.net    195.116.254.154
       www.tech.net     15.160.204.105
        
        if the ipAddress is 195.116.254.154 the output should be www.gmail.net
     */
    public String findDomainName(String ipAddress) 
    {
        String domain = null;
        for (Map.Entry<String, String> entry : domainMap.entrySet()) {
                String k = entry.getKey();
                String v = ipAddress;
                
                if (k.equals(v)) {
                    domain = k;                 
                }
         }     
         return domain;                 
    }
}

You actually compare the key to your ipAdress that's what you want, rather it's:您实际上将密钥与您想要的ipAdress进行比较,而不是:

public String findDomainName(String ipAddress) {
    String domain = null;
    for (Map.Entry<String, String> entry : domainMap.entrySet()) {
            String k = entry.getKey();
            String v = entry.getValue(); // <----  
            
            if (ipAddress.equals(v)) {
                domain = k;                 
            }
     }     
     return domain;                 
}

Can be shorten in可以缩短在

public String findDomainName(String ipAddress) {
    for (Map.Entry<String, String> entry : domainMap.entrySet()) 
            if (ipAddress.equals(entry.getValue())) 
                return entry.getKey();    
     return null; 
}

Using Streams使用流

public String findDomainName(String ipAddress) {
    return domainMap.entrySet().stream().filter(e -> ipAddress.equals(e.getValue()))
                    .map(Map.Entry::getKey).findFirst().orElse(null);
}

btw: First code returns last match, second code return first match顺便说一句:第一个代码返回最后一个匹配,第二个代码返回第一个匹配

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

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