在 stream.reduce 之后有没有更优雅的方式来切断主角?

Is there a more elegant way to chop of the leading character after a stream.reduce?

有没有更优雅的方法来连接流的元素,用“\n”分隔每个元素,但不是以“\n”开头,而不必像在以下示例?

    List<String> strings = someList;

    String rval = strings.stream()
            .map(this::someOperation)
            .reduce("", (p1, p2) -> p1 + "\n" + p2);

    if(rval.length() > 0)
    {
        // trim off the leading "\n"
        rval = rval.substring(1);
    }
    return rval;
}

当然我可以用内部循环代替它,但是那样会失去明显的功能可读性

使用

.collect(Collectors.joining("\n"))

它将通过不创建大量临时字符串和副本来解决您的问题,可读性更强,效率也更高。

有特定的收集器可以有效地处理字符串。如果您查看 Collectors.joining,您会发现它正是您要查找的内容:

String joined = strings.stream()
    .map(this::someOperation)
    .collect(Collectors.joining("\n"));