简体   繁体   中英

StringJoiner remove delimeter from first position for every line

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 (ie, 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()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM