2012-03-26 134 views
7
private static class FilterByStringContains implements Predicate<String> { 
     private String filterString; 
     private FilterByStringContains(final String filterString) { 
      this.filterString = filterString; 
     } 
     @Override 
     public boolean apply(final String string) { 
      return string.contains(filterString); 
     } 
    } 

我有一個字符串列表,我想通過指定的字符串進行過濾,所以返回的值只包含指定字符串的列表。我打算使用上面的謂詞,但不知道如何應用這個來過濾列表如何使用謂詞過濾列表

+0

看看這個[SO queston](http://stackoverflow.com/questions/587404/java-finding-objects-in-collections) - 聽起來就像你以後的樣子。你使用'Guava'還是'org.apache.commons.collections.Predicate'? – Attila 2012-03-26 18:45:38

+1

? – phanneman 2012-03-26 18:48:32

回答

10

我假設Predicate這裏是從Guava?如果是這樣,你可以使用Iterables.filter

Iterable<String> filtered = Iterables.filter(original, predicate); 

然後從建立一個列表,如果你想:

List<String> filteredCopy = Lists.newArrayList(filtered); 

...但我只建議將它複製到你的另一個列表實際上希望它成爲一個列表。如果你只是要遍歷它(並且只有一次),請堅持迭代。

4

如何使用Guava的filter方法或Apache公共的'filter方法? Guava的方法返回集合的視圖,而Apache Commons'就地修改集合。不要重新發明輪子!

+2

爲了澄清,番石榴的方法返回一個_view_,這是一個新的集合,但沒有明確的構造。 – 2012-03-26 18:57:10

+0

@LouisWasserman謝謝澄清,我編輯了我的答案。 – 2012-03-26 19:03:43