Guava中針對集合的 filter和過濾功能

在guava庫中,自帶了過濾器(filter)的功能,可以用來對collection 進行過濾,先看例子: 


  
Java代碼  收藏代碼
  1. @Test  
  2. public void whenFilterWithIterables_thenFiltered() {  
  3.     List<String> names = Lists.newArrayList("John""Jane""Adam""Tom");  
  4.     Iterable<String> result = Iterables.filter(names, Predicates.containsPattern("a"));  
  5.    
  6.     assertThat(result, containsInAnyOrder("Jane""Adam"));  
  7. }  

  在這個例子中,給出一個list,過濾出含有字母a的元素 

此外,可以使用Collections2.filter() 去進行過濾 
Java代碼  收藏代碼
  1. @Test  
  2. public void whenFilterWithCollections2_thenFiltered() {  
  3.     List<String> names = Lists.newArrayList("John""Jane""Adam""Tom");  
  4.     Collection<String> result = Collections2.filter(names, Predicates.containsPattern("a"));  
  5.        
  6.     assertEquals(2, result.size());  
  7.     assertThat(result, containsInAnyOrder("Jane""Adam"));  
  8.    
  9.     result.add("anna");  
  10.     assertEquals(5, names.size());  
  11. }  


  這裏注意的是,Collections2.filter中,當在上面的result中增加了元素後,會直接影響原來的names這個list的,就是names中的集合元素是5了。 
  再來看下predicates判斷語言, 
com.google.common.base. Predicate : 根據輸入值得到 true 或者 false 

拿Collections2中有2個函數式編程的接口:filter , transform ,例如 :在Collection<Integer>中過濾大於某數的內容: 


Java代碼  收藏代碼
  1. Collection<Integer> filterList = Collections2.filter(collections  
  2.   
  3.      , new Predicate<Integer>(){  
  4.   
  5.                   @Override  
  6.   
  7.                   public boolean apply(Integer input) {  
  8.   
  9.                         if(input > 4)  
  10.   
  11.                               return false;  
  12.   
  13.                         else  
  14.   
  15.                               return true;  
  16.   
  17.                   }  
  18.   
  19. });  



把Lis<Integer>中的Integer類型轉換爲String , 並添加test作爲後綴字符: 

Java代碼  收藏代碼
  1. List<String> c2 = Lists.transform(list, new Function<Integer , String>(){  
  2.   
  3.                   @Override  
  4.   
  5.                   public String apply(Integer input) {  
  6.   
  7.                         return String.valueOf(input) + "test";  
  8.   
  9.                   }              
  10.   
  11. });  




需要說明的是每次調用返回都是新的對象,同時操作過程不是線程安全的。 

    再來點例子: 
  
Java代碼  收藏代碼
  1. @Test  
  2. public void whenFilterCollectionWithCustomPredicate_thenFiltered() {  
  3.     Predicate<String> predicate = new Predicate<String>() {  
  4.         @Override  
  5.         public boolean apply(String input) {  
  6.             return input.startsWith("A") || input.startsWith("J");  
  7.         }  
  8.     };  
  9.    
  10.     List<String> names = Lists.newArrayList("John""Jane""Adam""Tom");  
  11.     Collection<String> result = Collections2.filter(names, predicate);  
  12.    
  13.     assertEquals(3, result.size());  
  14.     assertThat(result, containsInAnyOrder("John""Jane""Adam"));  
  15. }  

    將多個prdicate進行組合 
Java代碼  收藏代碼
  1. @Test  
  2. public void whenFilterUsingMultiplePredicates_thenFiltered() {  
  3.     List<String> names = Lists.newArrayList("John""Jane""Adam""Tom");  
  4.     Collection<String> result = Collections2.filter(names,   
  5.       Predicates.or(Predicates.containsPattern("J"),   
  6.       Predicates.not(Predicates.containsPattern("a"))));  
  7.    
  8.     assertEquals(3, result.size());  
  9.     assertThat(result, containsInAnyOrder("John""Jane""Tom"));  
  10. }  

   
     上面的例子中找出包含J字母或不包含a的元素; 
   
再看下如何將集合中的空元素刪除: 
  
Java代碼  收藏代碼
  1. @Test  
  2. public void whenRemoveNullFromCollection_thenRemoved() {  
  3.     List<String> names = Lists.newArrayList("John"null"Jane"null"Adam""Tom");  
  4.     Collection<String> result = Collections2.filter(names, Predicates.notNull());  
  5.    
  6.     assertEquals(4, result.size());  
  7.     assertThat(result, containsInAnyOrder("John""Jane""Adam""Tom"));  
  8. }  


    檢查一個collection中的所有元素是否符合某個條件: 
  
Java代碼  收藏代碼
  1. @Test  
  2. ublic void whenCheckingIfAllElementsMatchACondition_thenCorrect() {  
  3.    List<String> names = Lists.newArrayList("John""Jane""Adam""Tom");  
  4.   
  5.    boolean result = Iterables.all(names, Predicates.containsPattern("n|m"));  
  6.    assertTrue(result);  
  7.   
  8.    result = Iterables.all(names, Predicates.containsPattern("a"));  
  9.    assertFalse(result);  


   下面看如何把一個list進行轉換, 
Java代碼  收藏代碼
  1. @Test  
  2. public void whenTransformWithIterables_thenTransformed() {  
  3.     Function<String, Integer> function = new Function<String, Integer>() {  
  4.         @Override  
  5.         public Integer apply(String input) {  
  6.             return input.length();  
  7.         }  
  8.     };  
  9.    
  10.     List<String> names = Lists.newArrayList("John""Jane""Adam""Tom");  
  11.     Iterable<Integer> result = Iterables.transform(names, function);  
  12.    
  13.     assertThat(result, contains(4443));  
  14. }  

    
  再看結合transform和predicates結合使用的例子: 
  
Java代碼  收藏代碼
  1. @Test  
  2. public void whenCreatingAFunctionFromAPredicate_thenCorrect() {  
  3.     List<String> names = Lists.newArrayList("John""Jane""Adam""Tom");  
  4.     Collection<Boolean> result =  
  5.       Collections2.transform(names,  
  6.       Functions.forPredicate(Predicates.containsPattern("m")));  
  7.    
  8.     assertEquals(4, result.size());  
  9.     assertThat(result, contains(falsefalsetruetrue));  
  10. }  


    在這個例子中,將一個LIST中的每一個元素進行使用Predicates.containsPattern,判斷是否包含m,返回的是boolean,然後再得到的boolean值一起轉換爲collection 


    下面是兩個function一起結合使用的例子: 

 
Java代碼  收藏代碼
  1. @Test  
  2. public void whenTransformingUsingComposedFunction_thenTransformed() {  
  3.     Function<String,Integer> f1 = new Function<String,Integer>(){  
  4.         @Override  
  5.         public Integer apply(String input) {  
  6.             return input.length();  
  7.         }  
  8.     };  
  9.    
  10.     Function<Integer,Boolean> f2 = new Function<Integer,Boolean>(){  
  11.         @Override  
  12.         public Boolean apply(Integer input) {  
  13.             return input % 2 == 0;  
  14.         }  
  15.     };  
  16.    
  17.     List<String> names = Lists.newArrayList("John""Jane""Adam""Tom");  
  18.     Collection<Boolean> result = Collections2.transform(names, Functions.compose(f2, f1));  
  19.    
  20.     assertEquals(4, result.size());  
  21.     assertThat(result, contains(truetruetruefalse));  
  22. }  

   在這個例子中,首先應用函數f1,求出每個元素的長度,然後再根據f1函數,分別返回 
它們的boolean值,再轉換爲collection. 
   
   最後看下將filter和transform結合使用的例子: 
  
Java代碼  收藏代碼
  1. @Test  
  2. public void whenFilteringAndTransformingCollection_thenCorrect() {  
  3.     Predicate<String> predicate = new Predicate<String>() {  
  4.         @Override  
  5.         public boolean apply(String input) {  
  6.             return input.startsWith("A") || input.startsWith("T");  
  7.         }  
  8.     };  
  9.    
  10.     Function<String, Integer> func = new Function<String,Integer>(){  
  11.         @Override  
  12.         public Integer apply(String input) {  
  13.             return input.length();  
  14.         }  
  15.     };  
  16.    
  17.     List<String> names = Lists.newArrayList("John""Jane""Adam""Tom");  
  18.     Collection<Integer> result = FluentIterable.from(names)  
  19.                                                .filter(predicate)  
  20.                                                .transform(func)  
  21.                                                .toList();  
  22.    
  23.     assertEquals(2, result.size());  
  24.     assertThat(result, containsInAnyOrder(43));  
  25. }  

原文地址:http://jackyrong.iteye.com/blog/2150912
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章