I have a map:
Map<String, List<Object>> dataMap;
Now i want to add new key value pairs to the map like below:
if(dataMap.contains(key)) {
List<Object> list = dataMap.get(key);
list.add(someNewObject);
dataMap.put(key, list);
} else {
List<Object> list = new ArrayList();
list.add(someNewObject)
dataMap.put(key, list);
}
How can i do this with Java8 functional style?
HashMap get() Method in Java get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
To get the key and value elements, we should call the getKey() and getValue() methods. The Map. Entry interface contains the getKey() and getValue() methods. But, we should call the entrySet() method of Map interface to get the instance of Map.
To retrieve the set of keys from HashMap, use the keyset() method. However, for set of values, use the values() method.
You can use computeIfAbsent
.
If the mapping is not present, just create one by associating the key with a new empty list, and then add the value into it.
dataMap.computeIfAbsent(key, k -> new ArrayList<>()).add(someNewObject);
As the documentation states, it returns the current (existing or computed) value associated with the specified key so you can chain the call with ArrayList#add
. Of course this assume that the values in the original map are not fixed-size lists (I don't know how you filled it)...
By the way, if you have access to the original data source, I would grab the stream from it and use Collectors.groupingBy
directly.
This can be simplified by using the ternary operator. You don't really need the if-else statement
List<Object> list = dataMap.containsKey(key) ? dataMap.get(key) : new ArrayList<>();
list.add(someNewObject);
dataMap.put(key, list);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With