Is there anything like getOrDefault when putting a value into the java8 map?

hashmap getordefault example
java map
map.getordefault geeksforgeeks
java8 hashmap
java map values
putifabsent
map.get java
hashmap put

In java8, when getting some value from a map, we can write:

int keyCount=countMap.getOrDefault(key,0);

which is equal to:

if(countMap.contains(key)){
    keyCount=countMap.get(key);
}else{
    keyCount=0;
}

Problem is that is there any elegant way to replace below codes:

if(countMap.keySet().contains(key)){
    countMap.put(key,countMap.get(key)+1);
}else{
    countMap.put(key,1);
}

As holger mentioned as well, you can simply use Map.merge as :

countMap.merge(key, 1, Integer::sum)

Notice the documentation states its implementation as well:

The default implementation is equivalent to performing the following steps for this map, then returning the current value or null if absent:

V oldValue = map.get(key);
V newValue = (oldValue == null) ? value :
             remappingFunction.apply(oldValue, value);
if (newValue == null)
    map.remove(key);
else
    map.put(key, newValue);

HashMap: get() Vs. getOrDefault(), You may also like: How HashMap Works in Java In HashMap, get(Object key) method is used to retrieve the value of a key. So, instead of returning the null value, there should be some default value of the price. In But for this, we have to put an additional null check for each value in the product map. The getOrDefault(key, defaultValue) method of Properties class is used to get the value mapped to this key, passed as the parameter, in this Properties object. This method will fetch the corresponding value to this key, if present, and return it. If there is no such mapping, then it returns the defaultValue. Syntax:

You are looking for the compute method, also added in Java 8. That method takes in the key you are using, as well as a BiFunction to compute what the new value should be, based on the key and the existing value. So in your case, it would like something like the following:

countMap.compute(key, (k, oldValue) -> oldValue == null ? 1 : oldValue + 1);

When the key you give does not yet exist in the map, the oldValue in the BiFunction will be null; if you return null in the BiFunction, nothing gets put into the map.

It takes a little getting used to, but it's a very powerful method once you get the hang of it. It may be more readable (though much more verbose) with a method reference instead of the inline lambda:

    countMap.compute(key, this::incrementOrSetToOne);

    // ... some other code ...

    private Integer incrementOrSetToOne(KeyType key, Integer oldValue) {
        return oldValue == null ? 1 : oldValue + 1;
    }

HashMap getOrDefault(key, defaultValue) method in Java with , The getOrDefault(Object key, V defaultValue) method of Map interface, implemented by HashMap Return Value: This method returns value mapped with the specified key, otherwise default value is returned. map.put( "a" , 100 ); If you like GeeksforGeeks and would like to contribute, you can also write an article using� Hash_Map.put(key, value) Parameters: The method takes two parameters, both are of the Object type of the HashMap. key: This refers to the key element that needs to be inserted into the Map for mapping. value: This refers to the value that the above key would map into. Return Value: If an existing key is passed then the previous value gets

For those who are not familar with the merge method:

countMap.put(key, countMap.getOrDefault(key,0)+1);

Map (Java Platform SE 8 ), While it is permissible for a map to contain itself as a value, extreme caution is advised: In effect, the latter constructor allows the user to copy any map, producing an that of calling put(k, v) on this map once for each mapping from key k to value v in the specified map. default V getOrDefault(Object key, V defaultValue). java.util.HashMap put(K key, V value) Description : On this document we will be showing a java example on how to use the put() method of HashMap Class. Basically this method is to add key value pair to the HashMap object.

Java HashMap getOrDefault() method example, In dealing with HashMap methods, as a general rule you must always watch out for Generics The getOrDefault() method returns the value to which the specified key is mapped, mapStudent.put(98712, "Sharon Wallace");. getOrDefault(Object key, V defaultValue): This method returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key. merge(K key, V value, BiFunction<K, V> remappingFunction): This method If the specified key is not already associated with a value or is associated with null, associates it

Java 8, This tutorial explains Java 8 Map interface's new forEach(), replaceAll(), Next we will create a multi-value map which will serve as the base problem set In a hash table, there exists a mappping between a hash value(key) and Lets say we are adding a [key,value] entry to a multi-value map and the key� The following are Jave code examples for showing how to use getOrDefault() of the java.util.HashMap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.

Java Map and Subtleties of getOrDefault vs computeIfAbsent, As a reminder, before these 2 methods became available in Java 8, this String value = map.get("some key"); if( value == null ) { // do something if if( value == null ) { value = "some new string"; map.put( "some key", value ); }� Map.keySet() method returns a Set view of the keys contained in this map and Map.values() method returns a collection-view of the values contained in this map. So If you need only keys or values from the map, you can iterate over keySet or values using for-each loops. Below is the java program to demonstrate it.

Comments
  • Look at 'computeIfAbsent', part of the Map interface
  • Another variant countMap.put(key, countMap.containsKey(key) ? countMap.get(key) + 1 : 1);
  • It’s even simpler to use countMap.merge(key, 1, Integer::sum)
  • @Holger Yes it is. I always forget about merge. Thanks for noting it.