curiousengineer
curiousengineer

Reputation: 2607

StringBuilder's toString function with Java 8 streams

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

Upvotes: -3

Views: 109

Answers (2)

ETO
ETO

Reputation: 7279

Try using the plain-old approach instead of streams. It's more concise in this particular case:

var initialString = "zwdacb";
var chars = initialString.toCharArray();
Arrays.sort(chars);
var sortedString = new String(chars);

Upvotes: 0

Pablo Aragonés
Pablo Aragonés

Reputation: 608

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 an IntStream of the character values (ASCII values), and when you collect these values into a StringBuilder, they are treated as integer values.

Try with this:

public static void main(String[] args) {
    String s = "zwdacb";
    String sortedString = s.chars()
            .sorted()
            .collect(StringBuilder::new, (sb, c) -> sb.append((char) c), StringBuilder::append)
            .toString();
    System.out.println(sortedString);
}

Upvotes: 2

Related Questions