[JAVA] Optional Type conversion and return value (null support)

--Null support with parse

String args = "1";
Integer a = Optional.ofNullable(args).map(o -> Integer.parseInt(o)).orElse(999);
Integer b = Optional.ofNullable(args).map(o -> Optional.ofNullable(Integer.parseInt(o))).orElse(999);

--Asynchronous exceptions

List<Future<Void>> futures = new ArrayList<>();
for (ExecutorService service : ExecutorServices) {
    futures.add(service.async());
}
Exception exceptions = null;
for (Future<Void> future : futures) {
    try {
        future.get();
    } catch (InterruptedException | ExecutionException e) {
        exceptions = Optional.ofNullable(exceptions).map(exception -> {
            exception.addSuppressed(e);
            return exception;
        }).orElse(e);
    }
}

It was Optional to return with Optional.map Optional.flatMap requiresNonNull

public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
    Objects.requireNonNull(mapper);
    if (!isPresent())
        return empty();
    else {
        return Optional.ofNullable(mapper.apply(value));
    }
}
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
    Objects.requireNonNull(mapper);
    if (!isPresent())
        return empty();
    else {
        return Objects.requireNonNull(mapper.apply(value));
    }
}

Recommended Posts

Optional Type conversion and return value (null support)
null and optional types and ideals and reality
Conversion between Kotlin nullable and Java Optional
Mockito argument null Assuming test specified the type and did not return
Java study # 3 (type conversion and instruction execution)
[Java] Calculation mechanism, operators and type conversion
[Ruby] Difference between puts and return, output and return value
Java type conversion
Java Optional type
Java-automatic type conversion