3

I'm searching for an elegant way to stream only non-empty Optional entries using the StreamEx library. Or the standard library, if it's possible.

Currently I'm using the following, rather verbose, approach:

List<Optional<String>> list = 
   Arrays.asList(Optional.of("A"), Optional.empty(), Optional.of("B"));

List<String> nonEmpty = 
   StreamEx.of(list).filter(Optional::isPresent).map(Optional::get).toList();

I'm essentially looking for something like StreamEx's nonNull method, but for Optional.

4

2 回答 2

6

好吧,这已被添加,但仅在 java-9 中:

list.stream()
    .flatMap(Optional::stream)
    .collect(Collectors.toList());

这里有一个来自 Stuart Marks 的后向端口

于 2018-01-24T10:01:12.510 回答
2

对 StreamEx 问题积压的一些研究揭示了问题 49,它提供了一种较短的方法并包含对该主题的讨论:

List<String> nonEmpty = StreamEx.of(list).flatMap(StreamEx::of).toList();

更短,尽管它是否更具可读性还有待讨论。

于 2018-01-24T11:07:22.770 回答