Commons Collections - 物件過濾



Apache Commons Collections 庫的 CollectionUtils 類提供了各種實用方法,用於涵蓋廣泛用例的常見操作。它有助於避免編寫樣板程式碼。在 Java 8 的 Stream API 提供類似功能之前,此庫非常有用。

filter() 方法

CollectionUtils 的 filter() 方法可用於過濾列表,以移除不滿足傳遞的謂詞所提供條件的物件。

宣告

以下是

org.apache.commons.collections4.CollectionUtils.filter() 方法的宣告:

public static <T> boolean filter(Iterable<T> collection,
   Predicate<? super T> predicate)

引數

  • collection − 獲取輸入的集合,不能為 null。

  • predicate − 用作過濾器的謂詞,可以為 null。

返回值

如果此呼叫修改了集合,則返回 true,否則返回 false。

示例

以下示例演示了org.apache.commons.collections4.CollectionUtils.filter() 方法的用法。我們將過濾整數列表以僅獲取偶數。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;

public class CollectionUtilsTester {
   public static void main(String[] args) {
      List<Integer> integerList = new ArrayList<Integer>(); 
      integerList.addAll(Arrays.asList(1,2,3,4,5,6,7,8));
      System.out.println("Original List: " + integerList);
      CollectionUtils.filter(integerList, new Predicate<Integer>() {
         @Override
         public boolean evaluate(Integer input) {
            if(input.intValue() % 2 == 0) {
               return true;
            }
            return false;
         }
      });
      System.out.println("Filtered List (Even numbers): " + integerList);
   }
}

輸出

它將產生以下結果:

Original List: [1, 2, 3, 4, 5, 6, 7, 8]
Filtered List (Even numbers): [2, 4, 6, 8]

filterInverse() 方法

CollectionUtils 的 filterInverse() 方法可用於過濾列表,以移除滿足傳遞的謂詞所提供條件的物件。

宣告

以下是

org.apache.commons.collections4.CollectionUtils.filterInverse() 方法:

public static <T> boolean filterInverse(Iterable<T> collection, Predicate<? super T> predicate)

引數

  • collection − 獲取輸入的集合,不能為 null。

  • predicate − 用作過濾器的謂詞,可以為 null。

返回值

如果此呼叫修改了集合,則返回 true,否則返回 false。

示例

以下示例演示了org.apache.commons.collections4.CollectionUtils.filterInverse() 方法的用法。我們將過濾整數列表以僅獲取奇數。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;

public class CollectionUtilsTester {
   public static void main(String[] args) {
      List<Integer> integerList = new ArrayList<Integer>(); 
      integerList.addAll(Arrays.asList(1,2,3,4,5,6,7,8));
      System.out.println("Original List: " + integerList); 
      CollectionUtils.filterInverse(integerList, new Predicate<Integer>() {
         @Override
         public boolean evaluate(Integer input) {
            if(input.intValue() % 2 == 0) {
               return true;
            }
            return false;
         }
      });
      System.out.println("Filtered List (Odd numbers): " + integerList);
   }
}

輸出

結果如下所示:

Original List: [1, 2, 3, 4, 5, 6, 7, 8]
Filtered List (Odd numbers): [1, 3, 5, 7]
廣告