There are two maps
<Integer,String> map1
which is <ID,Question>
<Integer,String> map2
which is <ID,Answer>
I want to merge them into a single map <String,String> resultMap
which is <Question,Answer>
such that the Key in this map is the value from map1(Question) and value in resultMap is value from map2(Answer) and this is based on the same ID.
I can do this easily in java 6 as seen in below code.
for(Map.Entry<Integer,String> entry:map1.entrySet()){
qaMap.put(entry.getValue(),map2.get(entry.getKey()));
}
But I want to write this in Java 8 using streams and lambdas. How to do that?
We can use putAll() method on any map instance and put all the entries from the given map into it. First, we created an empty output map and then added all the entries from both of the maps into it. As a result, we got merged entries from both of our maps.
Assuming that both maps contain the same set of keys, and that you want to "combine" the values, the thing you would be looking for is a Pair class, see here for example. You simply iterate one of the maps; and retrieve values from both maps; and create a Pair; and push that in your result map.
Java HashMap merge() The Java HashMap merge() method inserts the specified key/value mapping to the hashmap if the specified key is already not present. If the specified key is already associated with a value, the method replaces the old value with the result of the specified function.
The easiest way to merge two maps in Groovy is to use + operator. This method is straightforward - it creates a new map from the left-hand-side and right-hand-side maps.
Well assuming your keys(IDs) are the same in both the maps we can do something like
Map<String,String> map = map1.keySet().stream()
.collect(Collectors.toMap(map1::get, map2::get));
map1.keySet().stream()
will get you a stream of IDs.collect(Collectors.toMap(map1::get, map2::get)
will create a Map from the stream of IDs with key as map1.get(id)
(i.e. your question) and value as map2.get(id)
(i.e. your answer) for each id.@above solution is elegant But someone should give alternative solution which should beginner to understand . So I could go with foreach
and lambda
.
You can iterate through Each map1
and add to the qaMap
.
Map<Integer,String> map1 = new HashMap<>();
Map<Integer,String> map2 = new HashMap<>();
Map<String,String> qaMap = new HashMap<>();
map1.put(1,"what is your age");
map2.put(1,"25");
map1.forEach((k,v)->qaMap.put(v,map2.get(k)));
System.out.println(qaMap.size());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With