将 int 数组转换为 String 数组

发布于 2024-09-16 12:59:17 字数 335 浏览 13 评论 0原文

所以我有这个整数“列表”。它可以是 Vectorint[]List 等。

但我的目标是对整数进行排序并最终得到一个 String[]。 int 数组如何开始尚无定论。

前任: 开头:{5,1,2,11,3} 结尾为: String[] = {"1","2","3","5","11"}

是否有办法在不使用 for 循环的情况下执行此操作?我现在有一个 for 循环来收集整数。我宁愿跳过另一个 for 循环。

So I have this "list" of ints. It could be a Vector, int[], List<Integer>, whatever.

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.

ex:
Start with:{5,1,2,11,3}
End with: 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

皓月长歌 2024-09-23 12:59:17
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));

更新:

较短的版本:

int[] nums = {-5,1,2,11,3};
Arrays.sort(nums);
String[] a=Arrays.toString(nums).split("[\\[\\]]")[1].split(", "); 
System.out.println(Arrays.toString(a));  
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));  
却一份温柔 2024-09-23 12:59:17

使用 Java 8 中提供的 Stream。要获取具有整数“列表”的 Stream 实例:

  • 对于 int[]
    • IntStream intStream = Arrays.Stream(nums);
    • 流<整数> intStream = Arrays.Stream(nums).boxed(); 如果您需要与底部相同的类。
  • 对于具有 Collection 接口的任何类(例如 VectorList
    • 流<整数> intStream = nums.stream();

最后,获取一个String[]

String[] answer = intStream.sorted().mapToObj(String::valueOf).toArray(String[]::new);

Use a Stream which is available from Java 8. To get a Stream instance with "list" of ints:

  • For int[]
    • IntStream intStream = Arrays.Stream(nums); or
    • Stream<Integer> intStream = Arrays.Stream(nums).boxed(); if you need the same class as bottom one.
  • For any classes with Collection<Integer> interface (ex. Vector<Integer>, List<Integer>)
    • Stream<Integer> intStream = nums.stream();

Finally, to get a String[]:

String[] answer = intStream.sorted().mapToObj(String::valueOf).toArray(String[]::new);
半山落雨半山空 2024-09-23 12:59:17

我可以使用 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);
}

使用 JUnit 断言。

抱歉,我太轻率了。但是说你不能使用 for 循环是愚蠢的 - 你必须以某种方式迭代列表。如果您要调用库方法来对其进行排序(参见 Collections.sort()) - 将以某种方式在元素上循环。

Can I use a while loop instead?

@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.

Sorry, I'm being flippant. But saying you can't use a for loop is daft - you've got to iterate over the list somehow. If you're going to call a library method to sort it for you (cf Collections.sort()) - that will be looping somehow over the elements.

同尘 2024-09-23 12:59:17

使用 Guava 的简单解决方案:

public List<String> toSortedStrings(List<Integer> ints) {
  Collections.sort(ints);
  return Lists.newArrayList(Iterables.transform(ints, 
      Functions.toStringFunction()));
}

显然,这个解决方案(与任何其他解决方案一样)将内部使用循环,但它可以从您必须阅读的代码中获取它。您还可以通过将 Ordering.natural().sortedCopy(ints) 的结果传递给 transform 而不是使用 ints 来避免更改 ints 中的顺序首先是Collections.sort。此外,如果您不需要向结果列表添加新元素,则不需要 Lists.newArrayList 部分。

该方法主体的缩短版本,带有静态导入:

return transform(Ordering.natural().sortedCopy(ints), toStringFunction());

Simple solution using 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.

The shortened version of that method body, with static imports:

return transform(Ordering.natural().sortedCopy(ints), toStringFunction());
萝莉病 2024-09-23 12:59:17

如果您使用 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

测试代码:

Set<Integer> items = new TreeSet<Integer>(Arrays.asList(5, 1, 2, 11, 3));

// insert above code here

System.out.println(Arrays.toString(arr));

输出:

[1, 2, 3, 5, 11]

编辑:

好的,这里是直接使用 int 数组的不同版本。但不幸的是,这不是一句俏话。但是,它确实保留了重复项,并且可能更快

再次编辑:

根据要求修复了错误并支持负数:

再次编辑:只有一次正则表达式传递,没有修剪

    final int[] in = { 5, 1, 2, 11, 3, 2, -5 }; // with duplicate
    Arrays.sort(in);
    final String[] out =
        Arrays.toString(in)
            .replaceAll("(?:\\[?)([-\\d]+)(?:\\]?)", "$1") // just remove [ and ]
            .split("\\s*,\\s*"); // split by comma

    System.out.println(Arrays.toString(out));

输出:

[-5, 1, 2, 2, 3, 5, 11]

或者完全没有正则表达式(除了 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));

输出:

[-5, 1, 2, 2, 3, 5, 11]

更新:从我的最后两个解决方案中删除了空格,希望您现在感到高兴:-)

If you use a TreeSet, I have a (longish) one-liner for you (assuming items is the 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

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]+)(?:\\]?)", "$1") // 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:

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 :-)

予囚 2024-09-23 12:59:17

我宁愿跳过再做一次
循环。

那太愚蠢了。这是进行代码练习的愚蠢愿望和愚蠢基础。如果你能更好地表达你希望你的代码具有的品质,那么我们就有话可说——它应该易于阅读,或者高性能,或者可测试,或者健壮。但“我宁愿跳过它”并没有给我们任何有用的东西。

I would rather skip doing another for
loop.

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.

无边思念无边月 2024-09-23 12:59:17

使用 函数式 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);

Using Functional 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);
喜你已久 2024-09-23 12:59:17

像这样的事情怎么样:

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);

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);
好菇凉咱不稀罕他 2024-09-23 12:59:17

使用 Eclipse 集合 MutableIntList

String[] result = IntLists.mutable.with(5, 1, 2, 11, 3)
        .sortThis()
        .collect(Integer::toString)
        .toArray(new String[]{});

Assert.assertArrayEquals(
        new String[]{"1", "2", "3", "5", "11"}, result);

或者用一些可读性来换取潜在的效率:

MutableIntList intList = IntLists.mutable.with(5, 1, 2, 11, 3).sortThis();
String[] result = intList.injectIntoWithIndex(
        new String[intList.size()], 
        (r, each, index) -> {
            r[index] = Integer.toString(each);
            return r;
        });

Assert.assertArrayEquals(
        new String[]{"1", "2", "3", "5", "11"}, result);

注意:我我是 Eclipse Collections 的提交者

Using Eclipse Collections MutableIntList:

String[] result = IntLists.mutable.with(5, 1, 2, 11, 3)
        .sortThis()
        .collect(Integer::toString)
        .toArray(new String[]{});

Assert.assertArrayEquals(
        new String[]{"1", "2", "3", "5", "11"}, result);

Or trading some readability for potential efficiency:

MutableIntList intList = IntLists.mutable.with(5, 1, 2, 11, 3).sortThis();
String[] result = intList.injectIntoWithIndex(
        new String[intList.size()], 
        (r, each, index) -> {
            r[index] = Integer.toString(each);
            return r;
        });

Assert.assertArrayEquals(
        new String[]{"1", "2", "3", "5", "11"}, result);

Note: I am a committer for Eclipse Collections

枕花眠 2024-09-23 12:59:17

我们可以使用正则表达式来解决这个问题,如下所示:

int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8};
String str = new String(Arrays.toString(intArray));
String stripNoneDigits= str.replaceAll("[^\\d]", "");
String[] stringArray = stripNoneDigits.split("");

We can solve this problem using regular expression as follows:

int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8};
String str = new String(Arrays.toString(intArray));
String stripNoneDigits= str.replaceAll("[^\\d]", "");
String[] stringArray = stripNoneDigits.split("");
╄→承喏 2024-09-23 12:59:17

您可以使用Collections.sort(),然后迭代列表并收集String.valueOf()每个元素。

http: //download.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29

对于 Vector,您首先需要使用 Collections.list(Enumeration e)

对于数组,您可以使用 Arrays.sort() 而不是 Collections.sort()。

http: //download.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort%28int%5b%5d%29

You can use Collections.sort() and then iterate over the list and collectString.valueOf() each element.

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).

For an array, you would use Arrays.sort() instead of Collections.sort().

http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort%28int%5b%5d%29

鸠魁 2024-09-23 12:59:17

为什么不在原始 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 ++;

}

或者,如果您两者都需要:

yourInt = someNumber;

for (int a = 0; a < aLimit; a ++) {

String stringName = String.valueOf(yourInt);
StringArrayName[a] = stringName;
intArrayName[a] = yourInt;
yourInt ++;

}

我同意其他人的观点。 For 循环很容易构造,几乎不需要任何开销来运行,并且在阅读代码时很容易理解。简约中透着优雅!

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.

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!

薄荷→糖丶微凉 2024-09-23 12:59:17

Java 8方式,根本没有循环:

 // Given
int[] array         = {-5, 8, 3, 10, 25};
// When
String[] actual = Arrays.stream(array)
        .sorted()
        .mapToObj(String::valueOf)
        .toArray(String[]::new);
// Then
String[] expected = {"-5", "3", "8", "10", "25"};

assertArrayEquals(expected, actual);

Java 8 way, no loops at all:

 // Given
int[] array         = {-5, 8, 3, 10, 25};
// When
String[] actual = Arrays.stream(array)
        .sorted()
        .mapToObj(String::valueOf)
        .toArray(String[]::new);
// Then
String[] expected = {"-5", "3", "8", "10", "25"};

assertArrayEquals(expected, actual);
最偏执的依靠 2024-09-23 12:59:17

Arrays.sort(nums);
var stringArray = (nums.toString()).split(',').map(String);

Arrays.sort(nums);
var stringArray = (nums.toString()).split(',').map(String);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文