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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:12:30  来源:igfitidea点击:

Converting List<Integer> to List<String>

javastringcollectionsinteger

提问by ChrisThomas123

I have a list of integers, List<Integer>and I'd like to convert all the integer objects into Strings, thus finishing up with a new List<String>.

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

Naturally, I could create a new List<String>and loop through the list calling String.valueOf()for each integer, but I was wondering if there was a better (read: more automatic) way of doing it?

自然地,我可以创建一个新的List<String>并循环调用String.valueOf()每个整数的列表,但我想知道是否有更好(阅读:更自动)的方法来做到这一点?

采纳答案by jsight

As far as I know, iterate and instantiate is the only way to do this. Something like (for others potential help, since I'm sure you know how to do this):

据我所知,迭代和实例化是唯一的方法。类似于(对于其他人的潜在帮助,因为我确定您知道如何执行此操作):

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

回答by jsight

@Jonathan: I could be mistaken, but I believe that String.valueOf() in this case will call the String.valueOf(Object) function rather than getting boxed to String.valueOf(int). String.valueOf(Object) just returns "null" if it is null or calls Object.toString() if non-null, which shouldn't involve boxing (although obviously instantiating new string objects is involved).

@Jonathan:我可能弄错了,但我相信 String.valueOf() 在这种情况下会调用 String.valueOf(Object) 函数而不是装箱到 String.valueOf(int)。String.valueOf(Object) 如果为 null 则只返回“null”,如果为 null 则调用 Object.toString() ,这不应该涉及装箱(尽管显然涉及实例化新的字符串对象)。

回答by ScArcher2

Instead of using String.valueOf I'd use .toString(); it avoids some of the auto boxing described by @johnathan.holland

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

The javadoc says that valueOf returns the same thing as Integer.toString().

javadoc 说 valueOf 返回与 Integer.toString() 相同的内容。

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

for (Integer myInt : oldList) { 
  newList.add(myInt.toString()); 
}

回答by Outlaw Programmer

I think using Object.toString() for any purpose other than debugging is probably a really bad idea, even though in this case the two are functionally equivalent (assuming the list has no nulls). Developers are free to change the behavior of any toString() method without any warning, including the toString() methods of any classes in the standard library.

我认为将 Object.toString() 用于调试以外的任何目的可能是一个非常糟糕的主意,即使在这种情况下,两者在功能上是等效的(假设列表没有空值)。开发人员可以在没有任何警告的情况下自由更改任何 toString() 方法的行为,包括标准库中任何类的 toString() 方法。

Don't even worry about the performance problems caused by the boxing/unboxing process. If performance is critical, just use an array. If it's really critical, don't use Java. Trying to outsmart the JVM will only lead to heartache.

甚至不用担心装箱/拆箱过程引起的性能问题。如果性能至关重要,只需使用数组。如果真的很重要,请不要使用 Java。试图超越 JVM 只会导致心痛。

回答by Mike Polen

The source for String.valueOf shows this:

String.valueOf 的来源显示了这一点:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

Not that it matters much, but I would use toString.

并不是说它很重要,但我会使用 toString。

回答by DrPizza

You can't avoid the "boxing overhead"; Java's faux generic containers can only store Objects, so your ints must be boxed into Integers. In principle it could avoid the downcast from Object to Integer (since it's pointless, because Object is good enough for both String.valueOf and Object.toString) but I don't know if the compiler is smart enough to do that. The conversion from String to Object should be more or less a no-op, so I would be disinclined to worry about that one.

你无法避免“拳击开销”;Java 的仿通用容器只能存储对象,因此您的整数必须装箱为整数。原则上它可以避免从 Object 到 Integer 的向下转换(因为它毫无意义,因为 Object 对 String.valueOf 和 Object.toString 都足够好)但我不知道编译器是否足够聪明来做到这一点。从 String 到 Object 的转换应该或多或少是一个空操作,所以我不愿意担心那个。

回答by serg10

Not core Java, and not generic-ified, but the popular Jakarta commons collections library has some useful abstractions for this sort of task. Specifically, have a look at the collect methods on

不是核心 Java,也不是泛型化的,但流行的 Jakarta 公共集合库为此类任务提供了一些有用的抽象。具体来说,看看收集方法

CollectionUtils

集合实用程序

Something to consider if you are already using commons collections in your project.

如果您已经在您的项目中使用公共集合,需要考虑一些事情。

回答by SCdF

What you're doing is fine, but if you feel the need to 'Java-it-up' you could use a Transformerand the collect methodfrom Apache Commons, e.g.:

您所做的很好,但是如果您觉得需要“Java-it-up”,您可以使用Transformer和来自Apache Commonscollect 方法,例如:

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

..and then..

..进而..

CollectionUtils.collect(
   collectionOfIntegers, 
   new IntegerToStringTransformer(), 
   newCollectionOfStrings);

回答by erickson

To the people concerned about "boxing" in jsight's answer: there is none. String.valueOf(Object)is used here, and no unboxing to intis ever performed.

对于 jsight 的回答中关注“拳击”的人:没有。String.valueOf(Object)在这里使用,并且int从未执行过拆箱。

Whether you use Integer.toString()or String.valueOf(Object)depends on how you want to handle possible nulls. Do you want to throw an exception (probably), or have "null" Strings in your list (maybe). If the former, do you want to throw a NullPointerExceptionor some other type?

您是否使用Integer.toString()String.valueOf(Object)取决于您希望如何处理可能的空值。你想抛出一个异常(可能),还是在你的列表中有“空”字符串(可能)。如果是前者,你想抛出 aNullPointerException还是其他类型?

Also, one small flaw in jsight's response: Listis an interface, you can't use the new operator on it. I would probably use a java.util.ArrayListin this case, especially since we know up front how long the list is likely to be.

另外,jsight 响应中的一个小缺陷:List是一个接口,您不能在其上使用 new 运算符。java.util.ArrayList在这种情况下,我可能会使用 a ,特别是因为我们预先知道列表可能有多长。

回答by Tom Hawtin - tackline

An answer for experts only:

仅针对专家的回答:

    List<Integer> ints = ...;
    String all = new ArrayList<Integer>(ints).toString();
    String[] split = all.substring(1, all.length()-1).split(", ");
    List<String> strs = Arrays.asList(split);