- 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?