Assume we are given:
Map<String, String> map1 = new HashMap<>(); map1.put("111","Frank"); map1.put("222","Ted"); map1.put("555","Peter"); Map<String, String> map2 = new HashMap<>(); map2.put("333","Roger"); map2.put("222","Ted"); map2.put("888","Kent"); map2.put("555","Peter");
How could I go about combining both of these into a new map:
Map<String, String> combinedMap = new HashMap<>();
I wanted to do it in a java stream way, so my attempt was:
combinedMap = Stream.of(map1, map2) .flatMap(m -> m.entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
But I was hit with some duplicate key error. I believe I could also just do a combinedMap.putAll(map1)
and combinedMap.putAll(map2)
but I'm not sure if that's the best way possible.
没有评论:
发表评论