简体   繁体   中英

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?

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);

You can also use compute method.

dataMap.compute(key, (k, v) -> {
                              if(v == null)
                                  return new ArrayList<>();
                              else {
                                   v.add(someNewObject);
                                   return v;
                              }
                         });

you can use

dataMap.compute(key,(k,v)->v!=null?v:new ArrayList<>()).add(someNewObject)

or

dataMap.merge(key,new ArrayList<>(),(v1,v2)->v1!=null?v1:v2).add(someNewObject)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM