Reputation: 101
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
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
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