如何用 Streams 替换 Iterables.filter()?

How to replace Iterables.filter() with Streams?

我正在尝试从 Guava 迁移到 Java 8 Streams,但不知道如何处理可迭代对象。这是我的代码,用于从可迭代对象中删除空字符串:

Iterable<String> list = Iterables.filter(
  raw, // it's Iterable<String>
  new Predicate<String>() {
    @Override
    public boolean apply(String text) {
      return !text.isEmpty();
    }
  }
);

注意,是 Iterable, not a Collection。它可能包含 无限 数量的项目,我无法将它们全部加载到内存中。我的 Java 8 选项是什么?

顺便说一句,使用 Lamba 这段代码看起来会更短:

Iterable<String> list = Iterables.filter(
  raw, item -> !item.isEmpty()
);

您可以使用 Stream.iterator()Iterable 实现为功能接口:

Iterable<String> list = () -> StreamSupport.stream(raw.spliterator(), false)
        .filter(text -> !text.isEmpty())
        .iterator();