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.

  • 2
    What happens when you have a duplicate key? – Boris the Spider Jan 27 '17 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 – Olivier Boissé Jan 27 '17 at 13:43
  • Take a look here: http://stackoverflow.com/questions/23038673/merging-two-mapstring-integer-with-java-8-stream-api – Emax Jan 27 '17 at 13:45
  • 1
    @oliv37 What is the advantage of that over [`mapurls#putAll`](https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#putAll-java.util.Map-)? – bradimus Jan 27 '17 at 13:45
  • @bradimus nothing, he wanted to use lambda expression. BTW you can write `repo.forEach(mapurls::put);` – Olivier Boissé Jan 27 '17 at 13:48
  • What is the following, can you show us the details or at least the simplified version? – Hearen Mar 28 '18 at 07:16

1 Answers1

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

Community
  • 1
  • 1
Naman
  • 27,789
  • 26
  • 218
  • 353