Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort String "13,5,8,4,2,1,9" in ascending order 1,2,4,5,8,9,13 in Java

Tags:

java

sorting

How can I sort a string "13,5,8,4,2,1,9" in ascending order, to get 1,2,4,5,8,9,13?

like image 423
mohan Avatar asked Mar 30 '10 07:03

mohan


People also ask

Can sort () sort strings?

The sort() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

How do I sort a String in Java 8?

The main logic is to toCharArray() method of the String class over the input string to create a character array for the input string. Now use Arrays. sort(char c[]) method to sort character array. Use the String class constructor to create a sorted string from a char array.


2 Answers

  • Split the string by commas
  • Parse each substring into an integer
  • Sort the resulting collection
  • If you need the result to be a string (it's not clear), convert each integer back into a string and join them together with commas.

If any of those steps causes you difficulties, please be more specific.

like image 178
Jon Skeet Avatar answered Sep 21 '22 02:09

Jon Skeet


  1. Split it into an array of items with String.split().
  2. Convert to an array of numbers with Integer.valueOf().
  3. Sort the array.
  4. Concatenate it all back into a StringBuilder.
like image 24
Marcelo Cantos Avatar answered Sep 18 '22 02:09

Marcelo Cantos