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 - 从中获取输入的集合可能不为
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]