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.example.util;
import java.util.Arrays;
import java.util.Collections;
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
// Collections.sort() method.
Collections.sort(Arrays.asList(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.toString());
}
}
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 create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020
- How do I get a list of all TimeZones Ids using Java 8? - April 25, 2020
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.