Guava
If you need Guava's ImmutableMap, you can make use of the Collector returned by ImmutableMap.toImmutableMap() available since Guava's version 21.0.
Note: the minimum JDK version required by the Guava 21.0 release is Java 8 (see), hence below is a valid Java 8 compliant solution.
public Map<String, String> getMap() {
return listOfKeys.stream()
.collect(ImmutableMap.toImmutableMap(
Function.identity(), // keyMapper - generating keys
str -> mapA.getOrDefault(str, ""), // valueMapper - generating values
(left, right) -> left // mergeFunction - resolving duplicates
));
}
In case if you're using Guava's version earlier than 21.0, then you can generate the resulting map using standard JDK collector toMap() and wrap it with an ImmutableMap by the means of collectingAndThen().
This approach would be cleaner, cramming the stream as an argument of the copyOf() method as suggested in another answer:
public Map<String, String> getMap() {
return istOfKeys.stream()
.collect(Collectors.collectingAndThen(
Collectors.toMap(
Function.identity(), // keyMapper - generating keys
str -> mapA.getOrDefault(str, ""), // valueMapper - generating values
(left, right) -> right), // mergeFunction - resolving duplicates
ImmutableMap::copyOf
));
}
Note:
If all elements contained in listOfKeys are guaranteed to be unique, then you can remove mergeFunction (the third argument of the collector).
I've replaced Objects.requireNonNullElse() with Map.getOrDefault() which would guard against the cases when a key is not present in the mapA. If you also want you protect against situations when the value associated with the key is null, then replace it with requireNonNullElse(). But you need to be aware that it's a sign of a faulty design if null values are being stored in the map because they have some special meaning in your business logic (and therefore you can't get rid of them).
Standard JDK
Otherwise, you can use collector Collectors.toUnmodifiableMap()
It internally uses a combination of collectors toMap(), accumulates stream data into a map, and collectingAndThen()) which performs the final transformation into a so-called unmodifiable map created via Map.ofEntries().
public Map<String, String> getMap() {
return listOfKeys.stream()
.collect(Collectors.toUnmodifiableMap(
Function.identity(), // keyMapper - generating keys
str -> mapA.getOrDefault(str, ""), // valueMapper - generating values
(left, right) -> left // mergeFunction - resolving duplicates
));
}
Map.copyOf