How to access objects outside of a lambda inside forEach?

I have the following code:

String fields = "";
listofObjects.stream().forEach(l -> fields = fields + l.text);

Which doesn't work, because fields should be final. How can I modify fields using lambdas?

Jon Skeet
people
quotationmark

The smallest change to make that work would just be to use a StringBuilder instead - and that would be more efficient:

StringBuilder builder = new StringBuilder();
listofObjects.stream().forEach(l -> builder.append(l.text));
String fields = builder.toString();

As Martin notes, Collectors.joining() provides general string joining capabilities, but you need to map your stream of objects to a stream of strings first. (Easy to do with map, and if you need to do this very often you could always create your own collector to do that.)

people

See more on this question at Stackoverflow