Converting an int array to a String array

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.


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


A shorter version:

int[] nums = {-5,1,2,11,3};
String[] a=Arrays.toString(nums).split("[\\[\\]]")[1].split(", "); 

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

Finally, to get a String[]:

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

Can I use a while loop instead?

public void test() {
    int[] nums = {5,1,2,11,3};


    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.

Simple solution using Guava:

public List<String> toSortedStrings(List<Integer> ints) {
  return Lists.newArrayList(Iterables.transform(ints, 

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

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



[1, 2, 3, 5, 11]


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
    final String[] out =
            .replaceAll("(?:\\[?)([-\\d]+)(?:\\]?)", "$1") // just remove [ and ]
            .split("\\s*,\\s*"); // split by comma



[-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
final String stringRep = Arrays.toString(in);
final String[] out =
    stringRep.substring(1, stringRep.length() - 1).split("\\s*,\\s*");



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

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,

import static*;
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);

How about something like this:

List<String> stringList = new ArrayList<String>();
List<Integer> list = new ArrayList<Integer>(Arrays.asList(5,1,2,11,3));
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()) {

Using Eclipse Collections MutableIntList:

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

        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;

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

Note: I am a committer for Eclipse Collections

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

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

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!

Java 8 way, no loops at all:

 // Given
int[] array         = {-5, 8, 3, 10, 25};
// When
String[] actual =
// 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); var stringArray = (nums.toString()).split(',').map(String);

Need Your Help

How do I check whether File.Delete() will succeed without trying it, in C#?

c# security permissions .net

In C#, System.IO.File.Delete(filePath) will either delete the specified file, or raise an exception. If the current user doesn't have permission to delete the file, it'll raise an

How to make part of a word bold in org-mode

emacs org-mode

How can I make org-mode markup work for a part of a word? For example, I'd like it to work for cases like this: