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]
广告
© . All rights reserved.