Search code examples
javajava-streamstringbuilder

Issue converting stringBuilder + forloop to stream + map


  • What I am trying to achieve:

I would like to convert a StringBuilder + forloop, like this:

public String question(List<MyPojo> myPojos) {
    final StringBuilder stringBuilder = new StringBuilder();
    for (MyPojo myPojo : myPojos) {
        try {
            String json = objectMapper.writeValueAsString(myPojo);
            stringBuilder.append(json).append("\n");
        } catch (JsonProcessingException e) {
                LOGGER.warn("bad");
        }
    }
    return stringBuilder.toString();
}

Into a stream() structure. This is not for performance, readability, or anything, I just want to try the conversion.

  • What did I try:
public String question(List<MyPojo> myPojos) {
    var stringBuilder = new StringBuilder();
    return myPojos.stream().map(onePojo -> delegate(onePojo, stringBuilder)).toString();
}

public StringBuilder delegate(MyPojo oneMyPojo, StringBuilder stringBuilder) {
    try {
        var json = objectMapper.writeValueAsString(oneMyPojo);
         stringBuilder.append(json).append("\n");
        } catch (JsonProcessingException e) {
                LOGGER.warn("bad");
    }
    return stringBuilder;
}
  • Issue

Unfortunately, the result string is not at all the same as the one provided by the for loop.

  • Question

What did I miss in my code?


Solution

  • You don't need a StringBuilder at all in your example, you can simply use .collect(Collectors.joining("\n")) to join your strings, your can can be like this:

    public String question(List<MyPojo> myPojos) {
        return myPojos.stream()
            .map(this::convertToJson) // Convert the object to json string
            .filter(json -> json != null && !json.isEmpty()) // retrieve non null or empty jsons
            .collect(Collectors.joining("\n")); // combine the result with backline separator
    }
    
    private String convertToJson(MyPojo myPojo) {
        try {
            return objectMapper.writeValueAsString(myPojo);
        } catch (JsonProcessingException e) {
            LOGGER.warn("bad");
            return "";
        }
    }