Reputation: 2761
Is there to map this, rather than looping through it? There are cases in which the value should not be put in the map, so I want to ignore those:
Map<A, String> returnMap = new HashMap<>();
Map<A, List<Long>> mapLByA = //...
mapLByA.forEach((k, v) -> {
Optional<String> strOp = someMethod(v);
if (str.isPresent()) {
returnMap.put(k, strOp.get());
}
});
return returnMap;
Upvotes: 1
Views: 2393
Reputation: 120848
You still need to loop, either externally or internally, no way around it. But you could simplify that code to a single line, cannot tell if it makes it more readable though:
mapLByA.forEach((k, v) -> someMethod(v).ifPresent(s -> returnedMap.put(k, s)));
Upvotes: 2
Reputation: 31878
You could simply use ifPresent
in the context as :
mapLByA.forEach((k, v) ->
someMethod(v).ifPresent(optional ->
returnMap.put(k, optional)));
Upvotes: 1
Reputation: 7917
You can map the list values to optional string values, then filter out the empty optionals, and finally collect to a map. You don't need to explicitly define returnMap
.
return mapLByA.entrySet().stream()
.map(e -> Map.entry(e.getKey(), someMethod(e.getValue())))
.filter(e -> e.getValue().isPresent())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
Edit:
Map.entry
was introduced in Java 9. For Java 8, use this map statement instead:
.map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), someMethod(e.getValue())))
Upvotes: 4