javascriptjavajava-streamreducebinary-operators

Using streams().reduce to build a string from ArrayList<Integer>?


In JavaScript we can build a string with other types using reducer (e.g. num to string):

const string = [1,2,3,4,5].reduce((acc,e) => acc += e, "") //"12345"

In Java, this pattern is not as easy when building a string from other types:

ArrayList<Integer> arrayListOfIntegers = (ArrayList<Integer>) Arrays.asList(1,2,3,4);
String string = arrayListOfIntegers.stream().reduce("", (String acc, Integer e) -> acc += e); // acc += e throws error

The error is:

"Bad return type: String cannot be converted to integer"

Is this pattern not possible in Java?


Solution

  • In Java, you can simply collect the Stream using Collectors.joining

    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class Main {
        public static void main(String[] args) {
            List<Integer> arrayListOfIntegers = Arrays.asList(1, 2, 3, 4);
            String str = arrayListOfIntegers.stream().map(String::valueOf).collect(Collectors.joining());
            System.out.println(str);
        }
    }
    

    Output:

    1234