Balzanka / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

Add new value to a map or return the original one #1331

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Some boiler-plate-code I often need is something like this:

{code}
public static <K, V> V putIfAbsent(Map<K, V> map, K key, V value) {
    V originalValue = map.get(key);
    if (originalValue == null) {
        originalValue = value;
        map.put(key, originalValue);
    }
    return originalValue;
}
{code}

Maybe I missed an already existing feature or it would be fine to add.

Greetings Danny 

Original issue reported on code.google.com by DannyLade on 12 Mar 2013 at 10:26

GoogleCodeExporter commented 9 years ago
This:

V originalValue = map.get(key);
    if (originalValue == null) {

Should be replaced with this:

if(!map.containsKey(key)){

After all, some Maps allow null values to be mapped.

Original comment by SeanPFl...@googlemail.com on 12 Mar 2013 at 10:38

GoogleCodeExporter commented 9 years ago
I disagree. For a null value allowing Maps used in a way allowing null values 
it might be necessary. Otherwise it probably wastes time by using both 
`contains` and `get`. So I'd suggest to use

    V originalValue = map.get(key);
    if (originalValue == null && !map.contains(key)) ...

instead (a benchmark needed?). An optimized implementation in Guava would be 
nice.

Original comment by Maaarti...@gmail.com on 13 Mar 2013 at 1:09

GoogleCodeExporter commented 9 years ago
Agree with comment #2

Original comment by SeanPFl...@googlemail.com on 14 Mar 2013 at 3:56

GoogleCodeExporter commented 9 years ago
Obviously ConcurrentMap already has a putIfAbsent() method. Interestingly, in 
JDK8 all Maps will have putIfAbsent() as well. (FWIW, the current default 
implementation of putIfAbsent() for Map in JDK8 is just "return 
containsKey(key) ? get(key) : put(key, value);")

Original comment by cgdec...@gmail.com on 14 Mar 2013 at 6:33

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<issue id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:12

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:18

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:08