获取带有空检查和功能的流以使用 orElse() 和 orElseThrow() 进行集合

Get stream with empty check and feature to use orElse() and orElseThrow() for collections

Optional.ofNullable() 仅检查 null 值,CollectionUtils.isNotEmpty() 不检查 return 流。有没有办法结合这两个功能。

像这样-

Collection.isNotEmpty(entries)
                .orElseThrow(() -> new Exception("exception"))
                .stream()

而不是-

Optional.ofNullable(entries)
                .orElseThrow(() -> new Exception("exception"))
                .stream()

也许:

Optional.ofNullable((entries == null || entries.isEmpty()) ? null : entries)
        .orElseThrow(() -> new Exception("exception"))
        .stream()

您可以将流映射为:

Optional.ofNullable(entries)
        .filter(a -> !a.isEmpty())
        .orElseThrow(() -> new Exception("exception"))
        // do whatever with the stream if available

您可以简单地使用 filter() 来检查它是否为空

Optional.ofNullable(entries)
    .filter(e -> !e.isEmpty())
    .orElseThrow(() -> new Exception("exception"))
    .stream()

关于您要消除流本身中的 null 值的评论,您可以使用此:

Optional.ofNullable(entries)
    .filter(e -> !e.isEmpty())
    .orElseThrow(() -> new Exception("exception"))
    .stream()
    .filter(Objects::nonNull)

为了比较,考虑这个:

if (entries == null || entries.isEmpty()) {
    throw Exception("exception");
} else {
    return entries.stream();
}

(Holger 在一些评论中提到了几乎相同的事情。)

在我看来,在这种情况下使用 Optional 并不是对传统 if/else 语句的改进。