目录

环境设置(Environment Setup)

Apache Commons Collections库的CollectionUtils类为常见操作提供了各种实用方法,涵盖了广泛的用例。 它有助于避免编写样板代码。 这个库在jdk 8之前非常有用,因为Java 8的Stream API现在提供了类似的功能。

转换列表

CollectionUtils的collect()方法可用于将一种类型的对象的列表转换为不同类型的对象的列表。

声明 (Declaration)

以下是声明

org.apache.commons.collections4.CollectionUtils.collect()方法

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

参数 (Parameters)

  • inputCollection - 从中获取输入的集合,可能不为null。

  • Transformer - 要使用的变换器,可以为null。

返回值 (Return Value)

转换结果(新列表)。

异常 (Exception)

  • NullPointerException - 如果输入集合为null。

例子 (Example)

以下示例显示了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);
   }
}

输出 (Output)

它将打印以下结果。

[1, 2, 3]
↑回到顶部↑
WIKI教程 @2018