As you're concatenating 3 different properties of the object, you need to use 3 different StringBuilder
instances (or StringJoiner
). You could iterate the list of objects 3 times, one for each property, or if you only want to iterate once (despite traversing a list is extremely cheap), you could use either your own approach or a traditional foreach.
Or you could also use the code I'm showing below, which is semantically equivalent to the other answers, except that it allows to decouple the concatenation process from the iteration (if you need this at all):
StringBuilder xBuilder = new StringBuilder(); // no need to use final since
StringBuilder yBuilder = new StringBuilder(); // these instances are
StringBuilder zBuilder = new StringBuilder(); // effectively final
Consumer<SomeObject> action = ((Consumer<SomeObject>) obj ->
xBuilder.append(obj.getX() + ","))
.andThen(obj -> yBuilder.append(obj.getY() + ","))
.andThen(obj -> zBuilder.append(obj.getA().getZ() + ","));
Then, you can pass around action
(i.e. to some method that doesn't have visibility over the builders) and simply do:
someObjects.forEach(action);