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

