Java 如何将字符串与新的1.8流API连接起来

Java 如何将字符串与新的1.8流API连接起来,java,java-8,java-stream,Java,Java 8,Java Stream,假设我们有一个简单的方法,该方法应该包含Person集合的所有名称并返回结果字符串 public String concantAndReturnNames(final Collection<Person> persons) { String result = ""; for (Person person : persons) { result += person.getName(); } return result; } 公共字符串c

假设我们有一个简单的方法,该方法应该包含Person集合的所有名称并返回结果字符串

public String concantAndReturnNames(final Collection<Person> persons) {
    String result = "";
    for (Person person : persons) {
        result += person.getName();
    }
    return result;
}
公共字符串concantAndReturnNames(最终收集人){
字符串结果=”;
用于(人:人){
结果+=person.getName();
}
返回结果;
}

有没有一种方法可以在一行中使用新的stream API forEach函数编写此代码?

有关您要执行的操作的官方文档:


参数传递给
收集器。加入
是可选的。

底部的代码块非常完美,可以完成我需要的一切:)谢谢!您可能希望使用String::valueOf而不是Object::toString来实现空安全性。
 // Accumulate names into a List
 List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());

 // Convert elements to strings and concatenate them, separated by commas
 String joined = things.stream()
                       .map(Object::toString)
                       .collect(Collectors.joining(", "));
 // Convert elements to strings and concatenate them, separated by commas
 String joined = persons.stream()
                       .map(Person::getName) // This will call person.getName()
                       .collect(Collectors.joining(", "));