简体   繁体   English

StringJoiner从每个行的第一个位置移除分隔符

[英]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): 您的记录分隔符是新行,因此您可能希望在for-each中使用逗号(即,交换新行和逗号的位置):

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? 为什么不直接覆盖Person类的toString方法或者在Person类中返回加入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()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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