0

I want to add two Map into the third map using lambda expression in java. following is my code. can anyone let me know how to do it.

I want above two maps into third map like Mapurls=repo+data

Please suggest me solution.

6
  • 2
    What happens when you have a duplicate key? Commented Jan 27, 2017 at 13:39
  • you could iterate over the two maps : repo.forEach((key, value) -> mapurls.put(key, value)); and data.forEach((key, value) -> mapurls.put(key, value)); if you have the same key in repo and data, the value of data will be stored Commented Jan 27, 2017 at 13:43
  • Take a look here: stackoverflow.com/questions/23038673/… Commented Jan 27, 2017 at 13:45
  • 1
    @oliv37 What is the advantage of that over mapurls#putAll? Commented Jan 27, 2017 at 13:45
  • @bradimus nothing, he wanted to use lambda expression. BTW you can write repo.forEach(mapurls::put); Commented Jan 27, 2017 at 13:48

1 Answer 1

1

Iterating through the key, values for each and adding them to finalMap should work -

Map<String, String> repo = TestRailReader.appendPathToUrl(urlRepo, CoreKeywords.REPO.name());
Map<String, String> data = TestRailReader.appendPathToUrl(urlData, CoreKeywords.DATA.name());
Map<String, String> mergedMap = new HashMap<>();
repo.forEach(mergedMap::put);
data.forEach(mergedMap::put);

Though the solution as suggested by @Emax in comments works better for the case when you need to merge. - Merging two Map<String, Integer> with Java 8 Stream API

Sign up to request clarification or add additional context in comments.

1 Comment

You are better off calling Map.putAll and letting the Map decide how it wants to loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.