membersound
membersound

Reputation: 86757

How to lazy init a Map in lambda functions?

I want to run a lambda function and collect a map of exceptions that occurred during the transformation.

Problem: I'd prefer not having to instantiate my Map before, because most computation runs will complete just without any error.

Thus, I'm trying to achieve the following:

Map<Integer, Throwable> errors;

Arrays.asList(1, 2, 3).stream().map(number -> {
    try {
        return heavyComputation(number);
    } catch (Exception ex) {
        if (errors == null) errors = new LinkedHashMap<>(); //TODO
        errors.put(number, ex);
        return null;
    }
}).collect(Collectors.toList());

Question: how can I lazy initialize my error Map?

Upvotes: 1

Views: 235

Answers (1)

Mikael Gueck
Mikael Gueck

Reputation: 5591

Change your approach a little. In your stream().map(), return a value-or-error container, rather than just the values. Look at CompletableFuture, for example.

Upvotes: 1

Related Questions