Commons Collections - 物件轉換



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

轉換列表

CollectionUtils 的 collect() 方法可用於將一種型別的物件列表轉換為不同型別的物件列表。

宣告

以下是用於

org.apache.commons.collections4.CollectionUtils.collect() 方法的宣告 −

public static <I,O> Collection<O> collect(Iterable<I> inputCollection, Transformer<? super I,? extends O> transformer)

引數

  • inputCollection − 用於獲取輸入的集合,不能為空。

  • Transformer − 要使用的轉換器,可以為空。

返回值

轉換後的結果(新列表)。

異常

  • NullPointerException − 如果輸入集合為空。

示例

以下示例演示了 org.apache.commons.collections4.CollectionUtils.collect() 方法的使用。我們將透過從 String 中解析整數值來將字串列表轉換為整數列表。

import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Transformer;

public class CollectionUtilsTester {
   public static void main(String[] args) {
      List<String> stringList = Arrays.asList("1","2","3");
      List<Integer> integerList = (List<Integer>) CollectionUtils.collect(stringList,
         new Transformer<String, Integer>() {
      
         @Override
         public Integer transform(String input) {
            return Integer.parseInt(input);
         }
      });
      System.out.println(integerList);
   }
}

輸出

使用程式碼時,你將得到以下程式碼 −

[1, 2, 3]
廣告