繁体   English   中英

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

[英]StringJoiner remove delimeter from first position for every line

我有以下代码:

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());
});

我想要的输出格式是:

Juan,Dela Cruz
Maria,Magdalena
Mario,Santos

但是,鉴于上述代码,结果是:

Juan,Dela Cruz
,Maria,Magdalena
,Mario,Santos

我如何摆脱分界符,作为每一行中的第一个字符?

谢谢。

另一种解决方案,使用流和连接收集器:

String result = persons.stream()
    .map(person -> person.getFirstName() + "," + person.getLastName())
    .collect(Collectors.joining(System.lineSeparator()));

您的记录分隔符是新行,因此您可能希望在for-each中使用逗号(即,交换新行和逗号的位置):

StringJoiner stringJoiner = new StringJoiner(System.lineSeparator());
...
persons.forEach(person -> stringJoiner.add(person.getFirstName() + 
            ", " + person.getLastName()));

为什么不直接覆盖Person类的toString方法或者在Person类中返回加入String的实用方法? 然后你的代码将完成迭代和合并的工作:

public static String getName(){
return String.format("%s,%s", this.firstName, this.lastName); 
}

然后使用以下或任何合适的机制来迭代和减少:

     persons.stream()
    .map(Person::getName)
    .collect(Collectors.joining(System.lineSeparator()));

暂无
暂无

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

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