Flattening a list of elements in Java 8 Optional pipeline
问题 I have a id value which can be null . Then I need to call some service with this id to get a list of trades and fetch the first not null trade from the list. Currently I have this working code Optional.ofNullable(id) .map(id -> service.findTrades(id)) .flatMap(t -> t.stream().filter(Objects::nonNull).findFirst()) .orElse(... default value...); Is it possible to implement a line with a flatMap call more elegantly? I don't want to put much logic in one pipeline step. Initially I expected to