Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java8 functional style, how can i map the values to already existing key value pair

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?

like image 643
parag mittal Avatar asked Dec 01 '15 13:12

parag mittal


People also ask

How does Java find the values with a given key in a map?

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.

How will you retrieve key value pair using HashMap?

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.

Which method is used to retrieve key and value pairs?

To retrieve the set of keys from HashMap, use the keyset() method. However, for set of values, use the values() method.


2 Answers

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.

like image 55
Alexis C. Avatar answered Nov 01 '22 18:11

Alexis C.


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);
like image 37
dkulkarni Avatar answered Nov 01 '22 16:11

dkulkarni