Lambda – merge different types of mappings into one in Java 8

There are two maps

>< integer, string > MAP1 is < ID, question > < integer, string > MAP2 is < ID, answer >

I want to merge them into a map < string, string > resultmap is < question, answer > so that the key in this map is the value in MAP1 (question), and the value in resultmap is the value in MAP2 (answer), which is based on the same ID

I can easily do this in Java 6, as shown in the following 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 in Java and Lambdas How do you do it?

Solution

Assuming that your key (ID) is the same in two maps, we can do similar things

Map<String,String> map = map1.keySet().stream()
    .collect(Collectors.toMap(map1::get,map2::get));

>In the above statement, MAP1 keySet(). Stream() will provide you with the ID stream. > Then, the collectors. Tomap (MAP1:: get, MAP2:: get) will create a map from the ID stream, where the key is MAP1 Get (ID) (i.e. your question), the value is MAP2 Get (ID) (your answer) each ID

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>