CCC
CCC

Reputation: 2761

ignoring null or Optional.empty values when mapping

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

Answers (3)

Eugene
Eugene

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

Naman
Naman

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

Kartik
Kartik

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

Related Questions