将List <Integer>转换为List <String>

Chr*_*123 96 java string collections integer

我有一个整数列表,List<Integer>我想将所有整数对象转换为字符串,从而完成一个新的List<String>.

当然,我可以创建一个新的List<String>循环遍历列表调用String.valueOf()每个整数,但我想知道是否有更好的(读取:更自动)的方式吗?

Ben*_*ngs 92

使用Guava-Project中的Google Collections,您可以使用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());
Run Code Online (Sandbox Code Playgroud)

List通过返回transform是一个视图背衬列表上-变换将在每个访问变换表来施加.

请注意,当应用于null时Functions.toStringFunction()将抛出一个NullPointerException,因此只有在确定列表不包含null时才使用它.

  • HotSpot可以内联函数调用 - 所以如果调用它足够多,它应该没有区别. (3认同)
  • 我不赞成这一点,因为它确实是一种解决方案.但鼓励人们添加库依赖来解决这么简单的任务对我来说是不行的. (3认同)

jsi*_*ght 76

据我所知,迭代和实例化是唯一的方法.有点像(对于其他潜在的帮助,因为我确定你知道如何做到这一点):

List<Integer> oldList = ...
/* Specify the size of the list up front to prevent resizing. */
List<String> newList = new ArrayList<String>(oldList.size()) 
for (Integer myInt : oldList) { 
  newList.add(String.valueOf(myInt)); 
}
Run Code Online (Sandbox Code Playgroud)


Tre*_*kaz 73

Java 8的解决方案比Guava的解决方案长一点,但至少你不必安装库.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

//...

List<Integer> integers = Arrays.asList(1, 2, 3, 4);
List<String> strings = integers.stream().map(Object::toString)
                                        .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)


SCd*_*CdF 40

你在做什么是好的,但如果你觉得有必要的Java-它一起"你可以使用一个变压器收集方法,从Apache的共享,例如:

public class IntegerToStringTransformer implements Transformer<Integer, String> {
   public String transform(final Integer i) {
      return (i == null ? null : i.toString());
   }
}
Run Code Online (Sandbox Code Playgroud)

..然后..

CollectionUtils.collect(
   collectionOfIntegers, 
   new IntegerToStringTransformer(), 
   newCollectionOfStrings);
Run Code Online (Sandbox Code Playgroud)

  • 除非在apache集合上做了新的工作,否则他们不做泛型. (5认同)

ScA*_*er2 9

而不是使用String.valueOf我使用.toString(); 它避免了@ johnathan.holland描述的一些自动拳击

javadoc说valueOf返回与Integer.toString()相同的东西.

List<Integer> oldList = ...
List<String> newList = new ArrayList<String>(oldList.size());

for (Integer myInt : oldList) { 
  newList.add(myInt.toString()); 
}
Run Code Online (Sandbox Code Playgroud)


Mik*_*len 9

String.valueOf的来源显示了这个:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}
Run Code Online (Sandbox Code Playgroud)

并不重要,但我会使用toString.


Gar*_*all 9

这是一个单行解决方案,没有与非JDK库作弊.

List<String> strings = Arrays.asList(list.toString().replaceAll("\\[(.*)\\]", "$1").split(", "));
Run Code Online (Sandbox Code Playgroud)


san*_*den 6

另一个使用Guava和Java 8的解决方案

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<String> strings = Lists.transform(numbers, number -> String.valueOf(number));
Run Code Online (Sandbox Code Playgroud)