Search code examples
javastringjava-8java-streamstringbuilder

How to use StringBuilder inside the reduce method in java 1.8?


String s = "apples for you";
StringBuilder returnString = new StringBuilder("");
Arrays.stream(s.split(" "))
        .reduce(returnString, (acc, str) -> acc.append(str.charAt(0)));

Expected output first letter of each word, i.e. afy.

But getting error at acc.append, acc is treated to be a String.


Solution

  • Your use of reduce is incorrect. The overload you intend to call is the one with 3 parameters, which should also take a binary operator for StringBuilder:

    StringBuilder returnString = Arrays.stream(s.split(" "))
            .reduce(new StringBuilder(""), 
                    (acc, str) -> acc.append(str.charAt(0)), 
                    (sb1, sb2) -> sb1.append(sb2));
    

    If you're to use this on a parallel stream, please perform a mutable reduction (with stream.collect) as the initial, identity string builder object may otherwise be appended to unpredictably from multiple threads:

    StringBuilder returnString = Arrays.stream(s.split(" "))
            .collect(StringBuilder::new, 
                     (acc, str) -> acc.append(str.charAt(0)), 
                     StringBuilder::append);