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