Task - Stream API - Merging Maps #54
Replies: 16 comments
-
|
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
|
import java.util.; public class Merge { } |
Beta Was this translation helpful? Give feedback.
-
|
import java.util.List; public class MergeMaps { } |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MergeMaps {
public static void main(String[] args) {
Map<Integer, String> map1 = new HashMap<>();
map1.put(1, "A");
map1.put(2, "B");
Map<Integer, String> map2 = new HashMap<>();
map2.put(1, "C");
map2.put(2, "D");
Map<Integer, List<String>> mergedMap = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream())
.collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
System.out.println(mergedMap);
}
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
You have two maps
m1andm2of typeMap<Integer, String>, which have to be merged into a single map of typeMap<Integer, List<String>>, where values of the same keys in both the maps are collected into aListand put into a newMap.Sample map
m1{ 1 = "A", 2 = "B" }Sample map
m2{ 1 = "C", 2 = "D" }Expected Output
{ 1 = [A, C], 2 = [B, D] }Hint
For ideas, you can refer to Java groupingBy collector.
Beta Was this translation helpful? Give feedback.
All reactions