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?

2

2 Answers 2

2

Yes, you can do this like that:

final String s = "cba";
final String collect = Arrays.stream(s.split(""))
            .sorted()
            .collect(Collectors.joining(""));
Sign up to request clarification or add additional context in comments.

Comments

2

You can use IntStream from String.chars()

    "cba"
            .chars()
            .sorted()
            .mapToObj(value -> (char) value)
            .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
            .toString()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.