'Map<String, List<String, Object>> add new list entry when key exists

Let's say I got Map<ID, Object> when looping over the entries via .entrySet().stream()

I want to map it to Map<String, List<Map<String, Object>>

When using toMap() I change the ID of my initial map to a String (with a database call), but different ID's can return the same string so there can be duplicates. Is it possible if my key already exists in the toMap of my new map that I'm collecting, that my ObjectOne is added in a new list entry of my new map in the format of Map<String, List<Map<String, Object>> .

I tried stuff with Collectors.groupingBy() and Collectors.mapping() but not getting it to work, curious if there is a way to do this

What I got now is the following solution, but I would like to collect it to map without having to define it first:

  Map<String, List<Map<String, Object>>> giantMap = new HashMap<>();
   
  initalMap.forEach((id, object) -> {
      Code code = repository.getCodeById(id);
      giantMap.computeIfAbsent(code, ignore -> new ArrayList<>())
                        .add(object);
   });


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source