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

前端 未结 4 800
抹茶落季
抹茶落季 2020-11-29 12:27

I have a map:

Map> dataMap;

Now i want to add new key value pairs to the map like below:

i         


        
相关标签:
4条回答
  • 2020-11-29 12:40

    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.

    0 讨论(0)
  • 2020-11-29 12:40

    You can also use compute method.

    dataMap.compute(key, (k, v) -> {
                                  if(v == null)
                                      return new ArrayList<>();
                                  else {
                                       v.add(someNewObject);
                                       return v;
                                  }
                             });
    
    0 讨论(0)
  • 2020-11-29 12:45

    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)
    
    0 讨论(0)
  • 2020-11-29 12:49

    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);
    
    0 讨论(0)
提交回复
热议问题