简体   繁体   English

将int数组转换为String数组

[英]Converting an int array to a String array

So I have this "list" of ints. 所以我有这个整数的“清单”。 It could be a Vector , int[] , List<Integer> , whatever. 它可以是Vectorint[]List<Integer>等等。

My goal though is to sort the ints and end up with a String[] . 我的目标是对int进行排序并最终得到一个String[] How the int array starts out as is up in the air. 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? 反正没有for循环吗? I have a for loop now for collecting the ints. 我现在有一个for循环用于收集整数。 I would rather skip doing another for loop. 我宁愿跳过另一个for循环。

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

Use a Stream which is available from Java 8. To get a Stream instance with "list" of ints: 使用Java 8中提供的Stream 。要获取具有整数“list”的Stream实例:

  • For int[] 对于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> ) 对于具有Collection<Integer>接口的任何类(例如Vector<Integer>List<Integer>
    • Stream<Integer> intStream = nums.stream();

Finally, to get a String[] : 最后,获取String[]

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

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 iterate over the list somehow. 但是说你不能使用for循环是愚蠢的 - 你必须以某种方式迭代列表。 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. 如果您打算调用库方法为您排序(cf Collections.sort() ) - 那将以某种方式循环元素。

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. 您还可以通过将Ordering.natural().sortedCopy(ints)的结果传递给transform而不是先使用Collections.sort来避免更改ints的顺序。 Also, the Lists.newArrayList part is not necessary if you don't need to be able to add new elements to the resulting list. 此外,如果您不需要能够将新元素添加到结果列表中,则Lists.newArrayList部分。

The shortened version of that method body, with static imports: 该方法体的缩短版本,带有静态导入:

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

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. 好的,这是一个直接与int数组一起使用的不同版本。 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: 或完全没有正则表达式 (除了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 :-) 更新:从我的最后两个解决方案剥离空白,希望你现在开心:-)

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. 但“我宁愿跳过它”只是没有给我们任何有用的东西。

Using Functional Java , 使用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);

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

Using Eclipse Collections MutableIntList : 使用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);

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 注意:我是Eclipse Collections的提交者

Why don't you simply cast those values to String within the original for loop, creating a String array rather than an int array? 为什么不简单地将这些值转换为原始for循环中的String,创建一个String数组而不是一个int数组? 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. 假设您从起始点收集初始整数并在每个for循环迭代中添加它,以下是创建String数组而不是int数组的简单方法。 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. 如果你需要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. For循环很容易构造,几乎不需要运行开销,并且在阅读代码时很容易理解。 Elegance in simplicity! 优雅简约!

You can use Collections.sort() and then iterate over the list and collect String.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,您首先会得到一个List with 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

Java 8 way, no loops at all: 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);

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM