Java 将 int 数组转换为 String 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3619850/
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
Converting an int array to a String array
提问by dev4life
So I have this "list" of ints. It could be a Vector
, int[]
, List<Integer>
, whatever.
所以我有这个整数“列表”。它可以是Vector
, int[]
, List<Integer>
, 等等。
My goal though is to sort the ints and end up with a String[]
. How the int array starts out as is up in the air.
我的目标是对整数进行排序并以String[]
. int 数组如何开始是悬而未决的。
ex:
Start with:{5,1,2,11,3}
End with: String[] = {"1","2","3","5","11"}
例如: 开始于:{5,1,2,11,3}
结束于:String[] = {"1","2","3","5","11"}
Is there anyway to do this without a for loop? I have a for loop now for collecting the ints. I would rather skip doing another for loop.
有没有办法在没有 for 循环的情况下做到这一点?我现在有一个 for 循环来收集整数。我宁愿跳过另一个 for 循环。
采纳答案by Emil
int[] nums = {5,1,2,11,3}; //List or Vector
Arrays.sort(nums); //Collections.sort() for List,Vector
String a=Arrays.toString(nums); //toString the List or Vector
String ar[]=a.substring(1,a.length()-1).split(", ");
System.out.println(Arrays.toString(ar));
UPDATE:
更新:
A shorter version:
一个较短的版本:
int[] nums = {-5,1,2,11,3};
Arrays.sort(nums);
String[] a=Arrays.toString(nums).split("[\[\]]")[1].split(", ");
System.out.println(Arrays.toString(a));
回答by gpeche
You can use Collections.sort()
and then iterate over the list and collectString.valueOf()
each element.
您可以使用Collections.sort()
然后遍历列表并收集String.valueOf()
每个元素。
http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29
http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29
For a Vector, you would first get a List with Collections.list(Enumeration e)
.
对于 Vector,您首先会得到一个带有Collections.list(Enumeration e)
.
For an array, you would use Arrays.sort()
instead of Collections.sort()
.
对于数组,您将使用Arrays.sort()
代替Collections.sort()
。
http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort%28int%5b%5d%29
http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort%28int%5b%5d%29
回答by Noel M
Can I use a while
loop instead?
我可以改用while
循环吗?
@Test
public void test() {
int[] nums = {5,1,2,11,3};
Arrays.sort(nums);
String[] stringNums = new String[nums.length];
int i = 0;
while (i < nums.length) {
stringNums[i] = String.valueOf(nums[i++]);
}
Assert.assertArrayEquals(new String[]{"1","2","3","5","11"}, stringNums);
}
Using JUnit assertions.
使用 JUnit 断言。
Sorry, I'm being flippant. But saying you can't use a for
loop is daft - you've got to iterateover the list somehow. If you're going to call a library method to sort it for you (cf Collections.sort()) - that will be looping somehowover the elements.
对不起,我轻率了。但是说你不能使用for
循环是愚蠢的——你必须以某种方式迭代列表。如果你要调用一个库方法来为你排序(参见Collections.sort()) - 这将以某种方式在元素上循环。
回答by Adam
How about something like this:
这样的事情怎么样:
List<String> stringList = new ArrayList<String>();
List<Integer> list = new ArrayList<Integer>(Arrays.asList(5,1,2,11,3));
Collections.sort(list);
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()) {
stringList.add(iterator.next().toString());
}
System.out.println(stringList);
回答by Sean Patrick Floyd
If you use a TreeSet, I have a (longish) one-liner for you (assuming items
is the TreeSet):
如果您使用 TreeSet,我为您准备了一个(较长的)单线(假设items
是 TreeSet):
final String[] arr =
items.toString() // string representation
.replaceAll("\D+", " ") // replace all non digits with spaces
.trim() // trim ends
.split(" "); // split by spaces
Test code:
测试代码:
Set<Integer> items = new TreeSet<Integer>(Arrays.asList(5, 1, 2, 11, 3));
// insert above code here
System.out.println(Arrays.toString(arr));
Output:
输出:
[1, 2, 3, 5, 11]
EDIT:
编辑:
OK, here is a different version that works with the int array directly. But unfortunately it's not a one-liner. However, it does keep duplicates and it's probably faster
好的,这是一个直接使用 int 数组的不同版本。但不幸的是,它不是单线。但是,它确实保留了重复项,而且速度可能更快
EDIT again:
再次编辑:
Bug fixed and negative numbers supported, as requested:
根据要求支持错误修复和负数:
EDIT once more: only one regex pass and no trim
再次编辑:只有一个正则表达式,没有修剪
final int[] in = { 5, 1, 2, 11, 3, 2, -5 }; // with duplicate
Arrays.sort(in);
final String[] out =
Arrays.toString(in)
.replaceAll("(?:\[?)([-\d]+)(?:\]?)", "") // just remove [ and ]
.split("\s*,\s*"); // split by comma
System.out.println(Arrays.toString(out));
Output:
输出:
[-5, 1, 2, 2, 3, 5, 11]
Or completely without regex(apart from split()), but with one more step added:
或者完全没有正则表达式(除了 split()),但又增加了一个步骤:
final int[] in = { 5, 1, 2, 11, 3, 2, -5 }; // with duplicate
Arrays.sort(in);
final String stringRep = Arrays.toString(in);
final String[] out =
stringRep.substring(1, stringRep.length() - 1).split("\s*,\s*");
System.out.println(Arrays.toString(out));
Output:
输出:
[-5, 1, 2, 2, 3, 5, 11]
Update: stripped whitespace from my last two solutions, hope you're happy now :-)
更新:从我的最后两个解决方案中删除了空格,希望你现在开心:-)
回答by Carl Manaster
I would rather skip doing another for loop.
我宁愿跳过另一个 for 循环。
That's silly. It's a silly desire and a silly basis for undertaking a code exercise. If you can better express the qualities that you want your code to have, then we've got something to talk about - that it should be easy to read, say, or performant, or testable, or robust. But "I'd rather skip it" just doesn't give us anything useful to work with.
那是愚蠢的。这是进行代码练习的愚蠢愿望和愚蠢的基础。如果你能更好地表达你希望你的代码具有的品质,那么我们有话要说——它应该易于阅读、易于表达、或性能良好、可测试或健壮。但是“我宁愿跳过它”并没有给我们任何有用的东西。
回答by ColinD
Simple solution using Guava:
使用Guava 的简单解决方案:
public List<String> toSortedStrings(List<Integer> ints) {
Collections.sort(ints);
return Lists.newArrayList(Iterables.transform(ints,
Functions.toStringFunction()));
}
Obviously, this solution (like any other) is going to use loops internally, but it gets it out of the code you have to read. You could also avoid changing the order in ints
by passing the result of Ordering.natural().sortedCopy(ints)
to transform
instead of using Collections.sort
first. Also, the Lists.newArrayList
part is not necessary if you don't need to be able to add new elements to the resulting list.
显然,这个解决方案(像任何其他解决方案一样)将在内部使用循环,但它从您必须阅读的代码中解脱出来。您还可以ints
通过传递Ordering.natural().sortedCopy(ints)
to的结果transform
而不是使用Collections.sort
first来避免更改顺序。此外,Lists.newArrayList
如果您不需要能够将新元素添加到结果列表中,则该部分不是必需的。
The shortened version of that method body, with static imports:
该方法主体的缩短版本,带有静态导入:
return transform(Ordering.natural().sortedCopy(ints), toStringFunction());
回答by missingfaktor
Using Functional Java,
使用函数式 Java,
import fj.data.List;
import static fj.data.List.*;
import static fj.pre.Show.*;
.
.
.
final List<Integer> xs = list(5,1,2,11,3);
final List<String> ys = xs.sort(Ord.intOrd).map(
new F<Integer, String>() {
@Override public String f(final Integer i) {
return String.valueOf(i);
}
}
);
listShow(stringShow).println(ys);
回答by elfinkind
Why don't you simply cast those values to String within the original for loop, creating a String array rather than an int array? Assuming that you're gathering your initial integer from a starting point and adding to it on each for loop iteration, the following is a simple methodology to create a String array rather than an int array. If you need both int and String arrays with the same values in them, create them both in the same for loop and be done with it.
为什么不在原始 for 循环中简单地将这些值转换为 String,创建一个 String 数组而不是一个 int 数组?假设您从起点收集初始整数并在每次 for 循环迭代中添加到它,以下是创建 String 数组而不是 int 数组的简单方法。如果您需要具有相同值的 int 和 String 数组,请在同一个 for 循环中创建它们并完成它。
yourInt = someNumber;
for (int a = 0; a < aLimit; a ++) {
String stringName = String.valueOf(yourInt);
StringArrayName[a] = stringName;
yourInt ++;
}
Or, if you need both:
或者,如果您同时需要:
yourInt = someNumber;
for (int a = 0; a < aLimit; a ++) {
String stringName = String.valueOf(yourInt);
StringArrayName[a] = stringName;
intArrayName[a] = yourInt;
yourInt ++;
}
I agree with everyone else. For loops are easy to construct, require almost no overhead to run, and are easy to follow when reading code. Elegance in simplicity!
我同意其他人。For 循环很容易构建,几乎不需要运行开销,并且在阅读代码时很容易理解。简约中的优雅!
回答by user1145927
Arrays.sort(nums); var stringArray = (nums.toString()).split(',').map(String);
Arrays.sort(nums); var stringArray = (nums.toString()).split(',').map(String);