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.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

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply