Apache通用集合转换对象

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

转换列表

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

声明

以下是org.apache.commons.collections4.CollectionUtils.collect()方法的声明 -

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

参数

  • inputCollection - 从中获取输入的集合可能不为null
  • transformer - 要使用的transformer可能为null

返回值

  • 换结果(新列表)。

示例

以下示例显示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]

上一篇:Apache通用集合合并与排序

下一篇:Apache通用集合过滤对象

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程