2017-01-30 49 views
9

我试图从番石榴迁移到Java 8 Streams,但无法弄清楚如何处理iterables。这里是我的代码,从迭代中删除空字符串:如何用Streams替换Iterables.filter()?

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

注意的是,这是一个Iterable,而不是Collection。它可能包含一个无限的项目数量,我无法将其全部加载到内存中。我的Java 8选择是什么?

BTW,与兰巴这段代码看起来更短:

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

是什么类型'raw'? – shmosel

+0

你上哪个版本的番石榴?或者你根本不想使用番石榴? – shmosel

+0

@shmosel我想摆脱Guava并迁移到Java 8 Streams,如果可能的话。也许不是。这就是为什么在这里问。 – yegor256

回答

8

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

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

'iterator()'返回'Iterator'的实例,而不是'Iterable' – yegor256

+1

@ yegor256请仔细阅读。或者试试看。 – shmosel

+1

明白了,我的不好。谢谢! – yegor256