James Verdune
James Verdune

Reputation: 101

How do you sort a string with lambda expressions in Java?

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?

Upvotes: 3

Views: 878

Answers (2)

Vlad Bochenin
Vlad Bochenin

Reputation: 3072

You can use IntStream from String.chars()

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

Upvotes: 2

MatWdo
MatWdo

Reputation: 1740

Yes, you can do this like that:

final String s = "cba";
final String collect = Arrays.stream(s.split(""))
            .sorted()
            .collect(Collectors.joining(""));

Upvotes: 2

Related Questions