tags:

views:

682

answers:

11

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?

+13  A: 
  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.
Marcelo Cantos
I'd use a StringBuilder; no need to incur the overhead of thread synchronization here.
extraneon
Thanks for tip, @extraneon. I've changed it.
Marcelo Cantos
+1 for mentioning method names; makes it the best answer most likely to lead to the questioner writing their own idiomatic code.
Donal Fellows
+1  A: 

So you have a string containing a comma-delimited set of integers that you need to sort and then output to a string? Try split-ting the string, parse-ing the integers, sort-ing the resulting array, and then join-ing the results together

Yuliy
+4  A: 

I would tokenize the string using StringTokenizer,
parse the values (using Integer.parseInt),
then sort the results using Arrays.sort.
Lastly, re-create the string.

geff_chang
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
codedevour
+25  A: 
  • 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.

Jon Skeet
A: 

This is one way to sorting.

package com.java;


import java.util.ArrayList;

import java.util.Collections;


public class b{

public static void main(String[] args) {
//create an ArrayList object

ArrayList arrayList = new ArrayList();


//Add elements to Arraylist

arrayList.add("9");
arrayList.add("3");
arrayList.add("5");
arrayList.add("2");
arrayList.add("4");

Collections.sort(arrayList);


//display elements of ArrayList

System.out.println("ArrayList elements after sorting in ascending order : ");

for(int i=0; i<arrayList.size(); i++)

System.out.println(arrayList.get(i));



}

}
Sanjeev
@Sanjeev where do you read in this string?
c0mrade
@c0mrade He doesn't. He demos the sorting.
extraneon
@extraneon I know he doesn't that's why I ask, this guy is probably looking something else to sort every now and then ..
c0mrade
@Sanjeev - sorting Strings will NOT work for this problem. Using the numbers given in the question this code will return `1 13 2 4 5 8 9`
Carlos Heuberger
@Sanjeev- Your program does not achieve what has been asked for.
Keshav
this won't work for comparing "1" and "13"
fuzzy lollipop
+2  A: 
String str = "13,5,8,4,2,1,9";
StringTokenizer tokens = new StringTokenizer(", ");
ArrayList<Integer> ints = new ArrayList<Integer>();
for(String token: tokens)
   ints.add(Integer.parseInt(token));

Collection.sort(ints);
String sortedStr = "";
for(int i = 0; i + 1 < ints.size(); ++i)
   sortedStr += ints.get(i) + ", ";
if (ints.size() > 0)
   sortedStr += ints.lastElement();

Might have some misspellings, but I think not. Also, add the appropriate imports yourself =)

Viktor Sehr
+1 for adding code sample
Atømix
-1 for suggesting StringTokenizer and not String.split()
fuzzy lollipop
well well, I actually had no idea StringTokenizer was deprecated. However, now I know =)
Viktor Sehr
+6  A: 

As one liner, using Google Collections (updated with Kevin's suggestion)

Joiner.on(",").join(Ordering.natural().onResultOf(new Function<String, Integer>() {
    @Override
    public Integer apply(String from) {
        return Integer.valueOf(from);
    }
}).sortedCopy(Arrays.asList("4,2,7,9,1".split(","))));
  • Split using String.split()
  • Transform to Integer using a Function (anyone know if there's a constant for this one somewhere?)
  • Sort using a TreeSet and natural ordering
  • Join the parts and transform back to a String using Joiner

(old version)

Joiner.on(',').join(
    Sets.newTreeSet(
        Iterables.transform(
            Arrays.asList("13,5,8,4,2,1,9".split(",")),
            new Function<String, Integer>() {
                @Override
                public Integer apply(String from) {
                    return Integer.parseInt(from);
                }}))));
Jorn
Cool, looks Lisp.
Viktor Sehr
Other ideas with GC/Guava: you could create an Ordering.natural().onResultOf(yourFunction), and use it like: ordering.sortedCopy(Splitter.on(',').split(input)).
Kevin Bourrillion
Sounds like a nice syntax, I'll try it out some time.
Jorn
@Kevin updated ;)
Jorn
Re: the Integer.valueOf() function, it will show up in Guava in a few months I think.
Kevin Bourrillion
cool, can't wait to see the other stuff they added
Jorn
A: 

Bash is SO powerful :-)

numbers="1, 2, 9, 4, 7, 5" ; for number in $(echo "$numbers") ; do echo "$number" | tr -d ", "; done | sort | tr "\n" "," ; echo ""

Emmef
except that the question was about Java...
NomeN
+3  A: 
String s = "13,5,8,4,2,1,9";
String[] arr = s.split(",");
Arrays.sort(arr, new Comparator<String>() {
   @Override public int compare(String s1, String s2) {
      return Integer.parseInt(s1) - Integer.parseInt(s2);
   }
});
s = Arrays.toString(arr).replaceAll("[\\[ \\]]", "");

This solution uses:

polygenelubricants
A: 

ok you can try this one it work in all case.

package com.java;

import java.util.*;

public class cd {
public static void main(String s[]) {
Collections col; List l = sort(s);

        System.out.println("\nStrings sorted List ...");
        for(int i = 0; i < s.length; i++)
        {
              System.out.println((String)l.get(i));
        }

        int ints[] = {
                                719, 2, -22, 401, 6
                                };

        Integer in[] = new Integer[ints.length];            
        for(int i = 0; i < in.length; i++)
        {
              in[i] = new Integer(ints[i]);
        }

        l = sort(in);
        System.out.println("\nIntegers sorted List ...");

        for(int i = 0; i < in.length; i++)
        {
              System.out.println((Integer)l.get(i));
        }
}

public static List sort(Object o[])
{
        ArrayList al = new ArrayList();
        for(int i = 0; i < o.length; i++)
        al.add(i, o[i]);
        List list = Collections.synchronizedList(al);
        Collections.sort(list);
        return list;
}

}

Sanjeev
A: 

An alternative using java.util.Scanner

public class SortString {
    public static void main( String [] args ) {
        // Read integers using Scanner...
        Scanner scanner = new Scanner( "13,5,8,4,2,1,9" ).useDelimiter(",");

        // Put them in a Integer list
        List<Integer> list = new ArrayList<Integer>();
        while( scanner.hasNextInt() ){
            list.add( scanner.nextInt() );
        }
        // And sort it
        Collections.sort( list );
        System.out.println( list );
    }
}
OscarRyz