我有一个整数列表,List<Integer>
我想将所有整数对象转换为字符串,从而完成一个新的List<String>
.
当然,我可以创建一个新的 List<String>
并循环调用列表 String.valueOf()
对于每个整数,但我想知道是否有更好的(阅读:更自动)方法?
最佳答案
使用 Google Collections from Guava-Project ,您可以使用 Lists 中的 transform
方法类
import com.google.common.collect.Lists;
import com.google.common.base.Functions
List<Integer> integers = Arrays.asList(1, 2, 3, 4);
List<String> strings = Lists.transform(integers, Functions.toStringFunction());
transform
返回的 List
是后备列表上的 view - 转换将应用于对已转换列表的每次访问。
请注意,Functions.toStringFunction()
在应用于 null 时会抛出 NullPointerException
,因此只有在您确定您的列表不包含 null 时才使用它。
关于java - 将 List<Integer> 转换为 List<String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18524/