I have the following codes:
StringJoiner stringJoiner = new StringJoiner(",");
List<Person> persons = Arrays.asList(new Person("Juan", "Dela Cruz"), new Person("Maria", "Magdalena"), new Person("Mario", "Santos"));
persons.forEach(person -> {
stringJoiner.add(person.getFirstName()).add(person.getLastName() + System.lineSeparator());
});
What I want its output format would be:
Juan,Dela Cruz
Maria,Magdalena
Mario,Santos
However, given the above codes, it results to:
Juan,Dela Cruz
,Maria,Magdalena
,Mario,Santos
How do I get rid of the delimiter ,
as the first character in every line?
Thank you.
An alternative solution, use streams and a joining collector:
String result = persons.stream()
.map(person -> person.getFirstName() + "," + person.getLastName())
.collect(Collectors.joining(System.lineSeparator()));
Your record delimiter is the new line, so you probably want to use the comma in the for-each (i.e., swap the places of new line and comma):
StringJoiner stringJoiner = new StringJoiner(System.lineSeparator());
...
persons.forEach(person -> stringJoiner.add(person.getFirstName() +
", " + person.getLastName()));
Why don't you just override toString method of Person class or have utility method in Person class that returns joined String? Then your code will simply do the job of iteration & merging:
public static String getName(){
return String.format("%s,%s", this.firstName, this.lastName);
}
And then use following or any suitable mechanism where you iterate and reduce:
persons.stream()
.map(Person::getName)
.collect(Collectors.joining(System.lineSeparator()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With