I want to optimize this solution (idiomatically).
I have a string containing only integer values. I want to convert this string into reverse int array. The output should be an integer array
Here is my solution:
private static int[] stringToReversedIntArray(String num) {
int[] a = new int[num.length()];
for (int i = 0; i < num.length(); i++) {
a[i] = Integer.parseInt(num.substring(i, i + 1));
}
a = reverse(a);
return a;
}
/*
* Reverses an int array
*/
private static int[] reverse(int[] myArray) {
int[] reversed = new int[myArray.length];
for (int i = 0; i < myArray.length; i++) {
reversed[i] = myArray[myArray.length - (i + 1)];
}
return reversed;
}
Input: "1256346258"
Output: {8,5,2,6,4,3,6,5,2,1}
Please suggest how to do same.
var input = "1256346258";
var result = Arrays
.stream(new StringBuffer(input).reverse().toString().split(""))
.map(Integer::parseInt)
.collect(Collectors.toList());
System.out.println(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With