Have a String
that I convert to IntStream
, sort it and get a StringBuilder
back. Upon calling toString
on it, I am seeing the concatenated ASCII values vs the sorted
characters in string format. Why is that? What is the fix?
class Solution {
public static void main(String[] args) {
String s = "zwdacb";
StringBuilder sb = s.chars()
.sorted()
.collect(() -> new StringBuilder(),
(x, y) -> x.append(y),
(StringBuilder sb1, StringBuilder sb2) ->
sb1.append(sb2));
System.out.println(sb.toString());
}
}
Output
979899100119122
The output you are seeing is the result of concatenating the ASCII values of the characters in the sorted order, rather than the characters themselves. This happens because the
sorted()
method returns anIntStream
of the character values (ASCII values), and when you collect these values into aStringBuilder
, they are treated as integer values.Try with this: