Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 207
Julez Avatar asked Mar 15 '19 11:03

Julez


3 Answers

An alternative solution, use streams and a joining collector:

String result = persons.stream()
    .map(person -> person.getFirstName() + "," + person.getLastName())
    .collect(Collectors.joining(System.lineSeparator()));
like image 186
nickb Avatar answered Oct 20 '22 13:10

nickb


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()));
like image 33
ernest_k Avatar answered Oct 20 '22 15:10

ernest_k


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()));
like image 1
Vinay Prajapati Avatar answered Oct 20 '22 14:10

Vinay Prajapati