0
0

More than 5 years have passed since last update.

Optional 型変換して値を返却(null 対応)

Last updated at Posted at 2019-02-25
  • parse で null 対応
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);
  • 非同期の exception まとめる
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);
    }
}

Optional.map で戻るのが Optional だった
Optional.flatMap は requireNonNull

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));
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0