0

The easiest way is to loop through, but that would be verbose and I would prefer a cleaner solution with Java 8.

This post over here recommends

mapCopy = map.entrySet().stream()
    .collect(Collectors.toMap(e -> e.getKey(), e -> List.copyOf(e.getValue())))

For copying HashMap<Integer, List>, but what I have is HashMap<String, HashMap<String, Integer>. I tried the above method for lists as well but for some reason, e.getKey() and e.getValue() both "cannot be resolved" even though IntelliJ auto-predicts it as a valid method, and e refers to a Map.Entry

I'm not super adept at using streams, so I can't figure out why the above doesn't work, or how to accomplish what I want.

protommxx
  • 57
  • 1
  • 9

1 Answers1

0

You can use the HashMap constructor to create a (shallow) copy of each value in the original Map.

Map<String, Map<String, Integer>> result = map.entrySet().stream()
   .collect(Collectors.toMap(Map.Entry::getKey, e -> new HashMap<>(e.getValue())));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80