Apache Commons Collections库的CollectionUtils类为常见操作提供了各种实用方法,涵盖了广泛的用例.它有助于避免编写样板代码.这个库在jdk 8之前非常有用,因为现在在Java 8的Stream API中提供了类似的功能.
collect()方法CollectionUtils可用于将一种类型的对象的列表转换为不同类型对象的列表.
以下是声明
org.apache.commons.collections4.CollectionUtils.collect()方法
public static <I,O> Collection<O> collect(Iterable<I> inputCollection, Transformer<? super I,? extends O> transformer)
inputCollection : 从中获取输入的集合可能不为空.
Transformer : 要使用的变换器可以为空.
转换结果(new列表).
NullPointerException &minus ;如果输入集合为空.
以下示例显示了组织的用法.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]