How do I sort string of numbers in ascending order?

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
Wayan

2 Comments

    • 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 the Long.parseLong() method a NumberFormatException will be thrown when the string exceeds the long range.

      try {
          long number = Long.parseLong("12345678901234567890");
      } catch (NumberFormatException e) {
          e.printStackTrace();
      }
      

      If you are working with a bigger number you might consider using the java.math.BigInteger instead.

      Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.