If I have to set values for a key (for many keys) in HashMap if not present then which one is better to use. getOrDefault() or putIfAbsent() As both the method will return the value associated with the key if it is already set. And both will take key,value pair as parameter.
23 Answers
Yes, they will both return the value associated with the key if it is already set, but one is only a getter while the other one is a setter.
putIfAbsent
If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
getOrDefault
Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
If your goal is only to retrieve the value, then use getOrDefault. Else, if you want to set the value when it does not exist, use putIfAbsent.
According to your first sentence,
If I have to set values for a key (for many keys) in HashMap if not present then which one is better
you should use putIfAbsent.
In Java8 There is also computeIfAbsent which returns the value if present or if it is absent it creates it through a lambda function, adds it to the Map and returns its value.
Value v = map.computeIfAbsent(key, k -> new Value(f(k))); 2getOrDefault() doesn't mutate the map, so you won't find the values in the map if you subsequently inspected its contents, e.g.
HashMap<String, String> map = new HashMap<>(); map.getOrDefault("something", "default"); // returns "default" assertTrue(map.isEmpty()); putIfAbsent() does mutate the map, so you would find the values in the map if you subsequently inspected its contents, e.g.
HashMap<String, String> map = new HashMap<>(); map.putIfAbsent("something", "default"); assertFalse(map.isEmpty()); You should pick the one appropriate to your needs.