简体   繁体   中英

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

Both Key and value are user input. Then value is passed to the as variable to retrieve the corresponding key for the value.

My output returns 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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