简体   繁体   中英

How to make Map Optional on whether its every optional value is present

I have a Map with many Optional values:

Map<MyCoolKey, Optional<MyCoolValue>>

I would like to transform this Map into an Optional<Map<>> :

Optional<Map<MyCoolKey, MyCoolValue>>
  • If every Optional<MyCoolValue> is present: the Optional<Map<>> should be present.
  • If any Optional<MyCoolValue> is non-present: the Optional<Map<>> should be non-present.

I attempted this, and I suspect that my code will work, but it's a bit long-winded:

final Map<MyCoolKey, Optional<MyCoolValue>> myCoolMap;
final Optional<Map<MyCoolKey, MyCoolValue>> optionalMap = myCoolMap
                .entrySet()
                .stream()
                .map(e -> e
                        .getValue()
                        .flatMap(value -> Optional.<Map.Entry<MyCoolKey, MyCoolValue>>of(
                                new AbstractMap.SimpleEntry<>(
                                        e.getKey(),
                                        value
                                )
                        ))
                )
                .collect(
                        () -> Optional.<Map<MyCoolKey, MyCoolValue>>of(new HashMap<>()),
                        (optAcc, optEntry) -> optAcc.flatMap(
                                acc -> optEntry.map(
                                        entry -> {
                                            acc.put(entry.getKey(), entry.getValue());
                                            return acc;
                                        })
                        ),
                        (optAcc1, optAcc2) -> optAcc1.flatMap(
                                acc1 -> optAcc2.map(
                                        acc2 -> {
                                            acc1.putAll(acc2);
                                            return acc1;
                                        }
                                )
                        )
                );

Is there a better way to do this? "Better" means correctness, performance, beauty. I would prefer an answer that can do the whole operation in one stream.

Here's an example of pure stream solution (without if s and ternary operators)

final Map<MyCoolKey, Optional<MyCoolValue>> myCoolMap = new HashMap<>();

Optional<Map<MyCoolKey, MyCoolValue>> output = Optional.of(myCoolMap)
    .filter(map -> map.values().stream().allMatch(Optional::isPresent))
    .map(map -> map
        .entrySet()
        .stream()
        .collect(toMap(
            Map.Entry::getKey,
            entry -> entry.getValue().get()
        ))
    );

It's not over-complicating - filtering and mapping are what's streams are for!

The following method does the job:

Map<MyCoolKey, Optional<MyCoolValue>> input;
Optional<Map<MyCoolKey, MyCoolValue>> output = convertMapWithOptionals(input);

where I came up with two "flavors" of this method:

1) Reluctant: first check all, then start converting

<K, V> Optional<Map<K, V>> convertMapWithOptionals(Map<K, Optional<V>> map) {
    if (!map.values().stream().allMatch(Optional::isPresent)) {
        return Optional.empty();
    }
    return Optional.of(map.entrySet().stream().collect(Collectors.toMap(
            Map.Entry::getKey, entry -> entry.getValue().get()
    )));
}

2) Eager: start converting and abort when necessary

<K, V> Optional<Map<K, V>> convertMapWithOptionals(Map<K, Optional<V>> map) {
    Map<K, V> result = new HashMap<>();
    for (Map.Entry<K, Optional<V>> entry : map.entrySet()) {
        if (!entry.getValue().isPresent()) {
            return Optional.empty();
        }
        result.put(entry.getKey(), entry.getValue().get());
    }
    return Optional.of(result);
}

If I understand question right, you can use reduce instead of collect . It would allows you to change accumulator during collect.

    Optional<Map<MyCoolKey, MyCoolValue>> optionalMap = myCoolMap
            .entrySet()
            .stream()
            .reduce(Optional.<Map<MyCoolKey, MyCoolValue>>of(new HashMap<>()),
                    (acc, entry) -> {
                        if (!acc.isPresent()) {
                            return acc;
                        }
                        if (!entry.getValue().isPresent()) {
                            return Optional.empty();
                        }
                        acc.get().put(entry.getKey(), entry.getValue().get());
                        return acc;
                    },
                    (acc, acc1) -> {
                        if (acc.isPresent() && acc1.isPresent()) {
                            acc.get().putAll(acc1.get());
                            return acc;
                        }
                        return Optional.empty();
                    }
            );

I think you've over-complicated it by trying to put all the logic in a stream. Just filter out the empty Optional s and see whether the number of elements is the same:

Optional<Map<MyCoolKey, MyCoolValue>> result = Optional.of(
    map.entrySet()
        .stream()
        .filter(e -> e.getValue().isPresent())
        .collect(
            Collectors.toMap(Map.Entry::getKey, e -> e.getValue().get())
        )
)
.filter(x-> x.size() == map.size());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM