- Commons Collections 教程
- Commons Collections - 首页
- Commons Collections - 总览
- Commons Collections - 环境设置
- Commons Collections - Bag 接口
- Commons Collections - BidiMap 接口
- Commons Collections - MapIterator 接口
- Commons Collections - OrderedMap 接口
- Commons Collections - 忽略 Null
- Commons Collections - 合并与排序
- Commons Collections - 对象转换
- Commons Collections - 过滤对象
- Commons Collections - 安全空检查
- Commons Collections - 包含
- Commons Collections - 交集
- Commons Collections - 差集
- Commons Collections - 并集
- Commons Collections 资源
- Commons Collections - 快速指南
- Commons Collections - 有用资源
- Commons Collections - 讨论
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]
广告