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?
views:
682answers:
11- Split it into an array of items with
String.split()
. - Convert to an array of numbers with
Integer.valueOf()
. - Sort the array.
- Concatenate it all back into a
StringBuilder
.
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
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.
- 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.
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));
}
}
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 =)
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 aFunction
(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
usingJoiner
(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);
}}))));
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 ""
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:
java.util.Comparator
java.util.Arrays
sort
andtoString
String
split
andreplaceAll
- regular expression
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;
}
}
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 );
}
}