如何使用新的1.8流API连接字符串

112
假设我们有一个简单的方法,应该将Person集合中所有人的姓名连接起来并返回结果字符串。
public String concantAndReturnNames(final Collection<Person> persons) {
    String result = "";
    for (Person person : persons) {
        result += person.getName();
    }
    return result;
}

有没有用新的流API forEach函数以一行代码编写此代码的方法?


考虑将其重命名为“在POJO集合上连接字符串标量属性”(使用新的...),因为我认为你的问题(以及被接受的答案)超出了“一个字符串”的范畴。今天我会给这个问题和最佳答案点赞。 - granadaCoder
1个回答

206

您想要做的内容的官方文档:https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html

 // 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(", "));

Collectors.joining方法的参数是可选的。


11
在那里,你可能希望使用String::valueOf而不是Object::toString,以实现空值安全性。 - okutane

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接