Tuesday, May 21, 2024
HomeJavaThe best way to replace worth for a given key in HashMap

The best way to replace worth for a given key in HashMap


Suppose you’ve gotten a Map of String keys and Integer values e.g. phrase and their depend. You might be studying from a file and storing depend of every phrase into an HashMap, if a phrase already exists you need to replace the worth by incrementing present worth by 1, how will you do this in Java? Does HashMap gives an replace() technique to carry out such operations? Nicely, No. HashMap would not present an replace technique however you need to use the identical put() technique to each insert and replace a mapping. For those who name the put(key, worth) technique with a key which already exists within the HashMap then as a substitute of including a brand new mapping, it updates the worth of present mapping. For instance, if the important thing “Java” is mapped to the worth 1000 in a map then calling put(“Java”, 1001) will change the outdated worth with the brand new worth, as a substitute of including one other entry. 
Bear in mind, you can not have duplicate keys in a HashMap, that is why you get a Set whenever you retrieve all keys and a Assortment whenever you retrieve all values, as a result of values might be duplicated in HashMap.

Btw, changing a price is little bit totally different than updating a price. In case of change, you understand the brand new worth and also you needn’t retrieve the outdated worth related to the important thing, however in case of replace you first must retrieve the prevailing worth for a given key, modify it e.g. increment or decrement it by 1 after which put it again once more into the map. 

That is like ++ operator, which first learn worth, increment it after which write it again to the variable.

While you ask a Java programmer to write down code for updating worth for given key in HashMap, you will notice many variations, lots of them are topic to NullPointerException as proven under:
hashmap.put(key, hashmap.get(key) + 1);
This code will throw NullPointerException for a non-existing key as a result of null can’t be autoboxed into zero therefore the null + 1 code will throw NullPointerException. One other comparable model is 
int worth = hashmap.get(key);
if (worth == null) {
    hashmap.put(key, 0);
} else {
    hashmap.put(key, worth + 1);
}
This code will additionally throw null pointer exception as a result of null can’t be auto-boxed into an int variable. The suitable approach, to replace a price in HashMap in Java is first to verify if key exists or not after which retrieve worth as proven in following instance:
if (hashmap.containsKey(key)) {
    hashmap.put(key, hashmap.get(key) + 1);
} else {
    hashmap.put(key, 1);
}

This code is not going to throw NullPointerException as we’re checking for the existence of key earlier than we retrieve worth from the Map.

Btw, Java 8 has added a helpful technique known as getOrDefault(), which might additional merely above code. This technique returns the worth to which the desired secret’s mapped, or default worth, if this map comprises no mapping for the important thing. You may rewrite the above code to replace a price in HashMap in only one line in Java 8 as proven under:
map.put(key, map.getOrDefault(key, 0) + 1);

This code makes use of the getOrDefault() technique of HashMap that retrieves the worth for a key, but when the important thing cannot be retrieved it returns the desired default worth (on this case a ‘0’).

How to update value for a given key in HashMap - Java 8 getOrDefault() example

Java Program to replace a key worth in HashMap

Right here is our full Java program to replace a price for given key in HashMap in each Java 8 and earlier than. The Java 8 approach is less difficult and clear however if you’re not working on Java 

import java.util.HashMap;
import java.util.Map;


public class Demo {

    public static void essential(String[] args) throws Exception {

        Map < String, Integer > wordCount = new HashMap < String, Integer > ();
        wordCount.put("Java", 0);

        wordCount.put("Java", wordCount.get("Java") + 1);

        System.out.println("map earlier than replace: " + wordCount);

        
        if (wordCount.containsKey("Java")) {
            wordCount.put("Java", wordCount.get("Java") + 1);
        } else {
            wordCount.put("Java", 0);
        }

        System.out.println("map after replace: " + wordCount);


        
        
        wordCount.put("Java", wordCount.getOrDefault("Java", 0) + 1);

        System.out.println("map after replace in Java 8: " + wordCount);
    }

}

Output

map earlier than replace: {Java=1}
map after replace: {Java=2}
map after replace in Java 8: {Java=3}

That is all about find out how to replace values in HashMap in Java. As I mentioned, In an effort to replace, you should first verify if key exists after which get the worth to keep away from NullPointerExceptoin. The identical put() technique is used to each insert and replace key worth pair in HashMap.

From Java 8 onwards, utilizing getOrDefault(key) as a substitute of get(key) is healthier alternative as you needn’t verify if a key exists in map or not. This technique return a default worth versus null which makes it safer to make use of. 

If you wish to be taught extra about such helpful adjustments in Java 8 See Java SE 8 for Actually Impatient, certainly one of my favourite e book for Java 8. 

Different Java HashMap tutorials you could prefer to discover:

  • How does get() technique of HashMap work in Java? (reply)
  • Distinction between ArrayList and HashMap? (distinction)
  • 3 methods to loop over a Map in Java? (instance)
  • HashSet vs HashMap in Java? (reply)
  • How HashSet internally works in Java? (reply)
  • HashMap vs LinkedHashMap in Java? (reply)
  • ArrayList vs HashMap in Java? (reply)
  • Distinction between ConcurrentHashMap and HashMap in Java? (reply)
  • The best way to type the HashMap on keys and values in Java? (answer)
  • How ConcurrentHashMap internally works in Java? (reply)
  • HashMap vs ConcurrentHashMap in Java? (reply)
  • One of the best ways to iterate over HashMap in Java? (reply)
  • Distinction between HashMap vs Hashtable in Java? (reply)
  • The best way to convert Map to Checklist in Java? (answer)

Thanks for studying this text up to now. For those who like this instance then please share with your pals and colleagues.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments