Converting an int array to a String array

76,963

Solution 1

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

Solution 2

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

Solution 3

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.

Solution 4

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

Solution 5

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

Share:
76,963

Related videos on Youtube

dev4life
Author by

dev4life

I likey the jquery.

Updated on July 09, 2022

Comments

  • dev4life
    dev4life almost 2 years

    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.

    • Darin Dimitrov
      Darin Dimitrov over 13 years
      Please retag your question with the appropriate language.
    • Paul Tomblin
      Paul Tomblin over 13 years
      Why do you want to avoid for loops? Any solution that anybody comes up with will have some sort of loop, even if it's hidden behind a method call.
    • ColinD
      ColinD over 13 years
      @Rudi It may have been edited within 5 minutes of being posted, in which case the edit wouldn't show up.
    • Javid Jamae
      Javid Jamae over 13 years
      To treat your fear of multiple for loops, I would seek professional help. Start by reading Refactoring (Martin Fowler) and Working Effectively With Legacy Code (Michael Feathers)...
  • gpeche
    gpeche over 13 years
    Oh, yes it is. I don't use Vector s that much as they are obsolete, so i didn't know they became List s. I remembered when you would iterate them with Vector.elements() (long ago).
  • ColinD
    ColinD over 13 years
    This won't work correctly for any array or list with more than 1 of the same element.
  • missingfaktor
    missingfaktor over 13 years
    +1 @ColinD. TreeSet will sort the numbers for you but it will also remove the duplicates, which is not what is intended.
  • Sean Patrick Floyd
    Sean Patrick Floyd over 13 years
    I know, but nobody said anything about keeping dupes
  • ColinD
    ColinD over 13 years
    Lists and arrays (mentioned in the question) keep duplicates, so I feel like it's kind of implicit.
  • Sean Patrick Floyd
    Sean Patrick Floyd over 13 years
    Vector, Hashtable, StringBuffer: These classes are all somewhat obsolete but folks keep using them. New folks, too. I wonder where they learn that...
  • Sean Patrick Floyd
    Sean Patrick Floyd over 13 years
    that's cool!! (if I had any remaining votes I'd upvote it) :-)
  • user85421
    user85421 over 13 years
    little changes needed for correctly handling negative numbers, and there is an undefined arr being used instead of in...
  • missingfaktor
    missingfaktor over 13 years
    @seanzier: Thanks, much appreciated! :)
  • Emil
    Emil over 13 years
    @seanizer: No need to handle the number's type in regex just remove the opening and closing braces and split with ", ".
  • Emil
    Emil over 13 years
    @seanizer:I have never heard StringBuffer to be obsolete.Can you refer to any article?
  • gpeche
    gpeche over 13 years
    StringBuilder obsoletes StringBuffer for most cases. download.oracle.com/javase/1.5.0/docs/api/java/lang/…
  • Sean Patrick Floyd
    Sean Patrick Floyd over 13 years
    @emil true, but I don't think that's any simpler
  • Emil
    Emil over 13 years
    Check my answer.I told so because you wouldn't have to handle negative values.
  • Emil
    Emil over 13 years
    Also leave a space after ',' other wise all numbers will have an extra space.
  • Sean Patrick Floyd
    Sean Patrick Floyd over 13 years
    @emil, ok here we go again. whitespace is now stripped
  • dev4life
    dev4life over 13 years
    I think this could be the answer. I didn't want to interate through the list a second time because I'm already iterating to get the int list. Thank you.
  • dev4life
    dev4life over 13 years
    Because I already loop to get the list. Thanks for playing though.
  • Emil
    Emil over 13 years
    if your concerned about speed then its better to use the normal for loop once more because in Arrays.toString() they are using a for loop.Check the source(docjar.com/html/api/java/util/Arrays.java.html) But if you just want your code to look small then ok,you can use the above code or another option is just write small function to sent an int[] as input and return String[] array as output.
  • user unknown
    user unknown about 12 years
    There a some problems with your code. 1. of all, nobody uses a blank in a++ while it might work. Don't try to be individual in coding style! 2. What is yourInt, someNumber? They don't exist in the question, and you don't declare or explain them. 3. casting is very narrowed defined term in Java. There is no cast from String to Int, because Int isn't a subclass of String. 4. nobody uses s[a]=String.valueOf (yourInt);, but s[a] = "" + yourInt;. 5. Why the intermediate assignment to stringName? 6. Why violation of coding styles and using StringArrayName[a] instead of stringArrayName[a]?
  • user unknown
    user unknown about 12 years
    7. What a name, stringArrayName! While it is an array of ints as names. 8. no indentation. All those problems hide your simple, but elegant, if applyable, idea.
  • Chance
    Chance over 9 years
    The "[\[\]]" is a regular expression, right? How did you know which one to use, and what exactly is it dictating?
  • Zach Lysobey
    Zach Lysobey over 8 years
    Don't think Java has the var keyword. This looks like JavaScript
  • FindOutIslamNow
    FindOutIslamNow almost 6 years
    The idea is to use Arrays.toString