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

前端 未结 4 810
抹茶落季
抹茶落季 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.

提交回复
热议问题