Is there a native way to sort a String by its contents in java? E.g.
String s = \"edcba\" -> \"abcde\"
Convert to array of chars → Sort → Convert back to String:
String s = "edcba";
char[] c = s.toCharArray(); // convert to array of chars
java.util.Arrays.sort(c); // sort
String newString = new String(c); // convert back to String
System.out.println(newString); // "abcde"
toCharArray
followed by Arrays.sort
followed by a String constructor call:
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
String original = "edcba";
char[] chars = original.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
System.out.println(sorted);
}
}
EDIT: As tackline points out, this will fail if the string contains surrogate pairs or indeed composite characters (accent + e as separate chars) etc. At that point it gets a lot harder... hopefully you don't need this :) In addition, this is just ordering by ordinal, without taking capitalisation, accents or anything else into account.
Question: sort a string in java
public class SortAStringInJava {
public static void main(String[] args) {
String str = "Protijayi";
// Method 1
str = str.chars() // IntStream
.sorted().collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
System.out.println(str);
// Method 2
str = Stream.of(str.split(" ")).sorted().collect(Collectors.joining());
System.out.println(str);
}
}
String a ="dgfa";
char [] c = a.toCharArray();
Arrays.sort(c);
return new String(c);
Note that this will not work as expected if it is a mixed case String (It'll put uppercase before lowercase). You can pass a comparator to the Sort method to change that.