3

I'm just learning about lambda expressions and I was wondering how to return a sorted string. For example, if I have "cba", I want "abc". Normally I would do:

String s = "cba";
char[] charList = s.toCharArray();
Arrays.sort(charList);
String sorted = charList.toString();

is there a way to do that in one line with lambda expressions?

James Verdune
  • 91
  • 1
  • 6

2 Answers2

2

Yes, you can do this like that:

final String s = "cba";
final String collect = Arrays.stream(s.split(""))
            .sorted()
            .collect(Collectors.joining(""));
MatWdo
  • 1,610
  • 1
  • 13
  • 26
2

You can use IntStream from String.chars()

    "cba"
            .chars()
            .sorted()
            .mapToObj(value -> (char) value)
            .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
            .toString()
Vlad Bochenin
  • 3,007
  • 1
  • 20
  • 33