Sort a single String in Java

后端 未结 10 949
误落风尘
误落风尘 2020-11-28 18:15

Is there a native way to sort a String by its contents in java? E.g.

String s = \"edcba\"  ->  \"abcde\"
10条回答
  •  孤独总比滥情好
    2020-11-28 18:49

    In Java 8 it can be done with:

    String s = "edcba".chars()
        .sorted()
        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
        .toString();
    

    A slightly shorter alternative that works with a Stream of Strings of length one (each character in the unsorted String is converted into a String in the Stream) is:

    String sorted =
        Stream.of("edcba".split(""))
            .sorted()
            .collect(Collectors.joining());
    

提交回复
热议问题