Remove all entries where value is an empty Optional from map

Yevhenii Semenov :

I want to remove all entries where value is an empty Optional from the map. It would seem that nothing complicated, but I am trying to find a better solution that I have.


Input:

I have the following Map:

Map<String, Function<String, Optional<String>>> attributesToCalculate = new HashMap<>();

Where key - just a String and value - reference to method which returns Optional < String >


Output:

As a result, I want to get

Map<String, String> calculatedAttributes

(excluding entries where value was an empty Optional)


Here is my solution

      return attributesToCalculate.entrySet()
        .stream()
        .map(entry -> Pair.of(entry.getKey(), entry.getValue().apply(someString)))
        .filter(entry -> entry.getValue().isPresent())
        .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().get()));

But I don't like the .filter part because then I have to invoke .get() on Optional in collect part.

Is there а better way (maybe without .get invocation) to solve this problem? Thanks.

Paul Boddington :

As commented above, there is nothing wrong with using get if you have already checked that the Optional is not empty.

However, I think this code is best expressed without using streams.

Map<String, String> result = new HashMap<>();
attributesToCalculate.forEach((k, v) ->
    v.apply(someString).ifPresent(str -> result.put(k, str))
);

If you don't like using forEach to populate the map in that way, you can use a simple for loop instead.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=440451&siteId=1