In the following example we are going to sort a string containing the following numbers "2, 5, 9, 1, 10, 7, 4, 8"
in ascending order, so we will get the result of "1, 2, 4, 5, 7, 8, 9, 10"
.
package org.kodejava.util;
import java.util.Arrays;
public class SortStringNumber {
public static void main(String[] args) {
// We have some string numbers separated by comma. First we
// need to split it, so we can get each individual number.
String data = "2, 5, 9, 1, 10, 7, 4, 8";
String[] numbers = data.split(",");
// Convert the string numbers into Integer and placed it into
// an array of Integer.
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
// Sort the number in ascending order using the
// Arrays.sort() method.
Arrays.sort(intValues);
// Convert back the sorted number into string using the
// StringBuilder object. Prints the sorted string numbers.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < intValues.length; i++) {
Integer intValue = intValues[i];
builder.append(intValue);
if (i < intValues.length - 1) {
builder.append(", ");
}
}
System.out.println("Before = " + data);
System.out.println("After = " + builder);
}
}
When we run the program we will get the following output:
Before = 2, 5, 9, 1, 10, 7, 4, 8
After = 1, 2, 4, 5, 7, 8, 9, 10
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
What will you do if any of the string exceeds long range?
Thank you!
Hi Navi,
When the string exceeds the long range I think it will not added to the list to be sorted. When trying to convert the string into
long
using theLong.parseLong()
method aNumberFormatException
will be thrown when the string exceeds the long range.If you are working with a bigger number you might consider using the
java.math.BigInteger
instead.