Sorting contents of a string that holds integer values in Java


To sort the string that contains numbers in java −

  • Get the String.

  • Create an empty integer array.

  • The split() method of the string class accepts a string representing a delimiter, splits the current string into an array of tokens. Using this method split the given string into an array of tokens.

  • The parseInt() method of the Integer class accepts a String value and converts it into an integer. Convert each element in the String array obtained in the previous step into an integer and store in into the integer array.

  • The sort() method of the Arrays class accepts an array, sorts the contents of it in ascending order. Sort the integer array using this method.

Example

public class SortingStrings {
   public static void main(String args[]) {
      String str = "22 58 69 63 69 55 669 24 4285 654 1 296 564 2 582 255 562";
      System.out.println("Contents of the string: "+ str);
      //Splitting the String array
      String[] stringArray = str.split(" ");
      //Converting each element into an integer
      int [] intArray = new int[stringArray.length];
      for(int i = 0; i < stringArray.length; i++) {
         intArray[i] = Integer.parseInt(stringArray[i]);
      }
      Arrays.sort(intArray);
      System.out.println("Sorted integer values: "+Arrays.toString(intArray));
   }
}

Output

Contents of the string: 22 58 69 63 69 55 669 24 4285 654 1 296 564 2 582 255 562
Sorted integer values: [1, 2, 22, 24, 55, 58, 63, 69, 69, 255, 296, 562, 564, 582, 654, 669, 4285]

Updated on: 11-Oct-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements