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

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

public String concantAndReturnNames(final Collection<Person> persons) {
String result = "";
for (Person person : persons) {
result += person.getName();
}
return result;
}

有没有一种方法来写这个代码与新的流 API 为每个函数在1行?

84680 次浏览

The official documentation for what you want to do: 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(", "));

For your example, you would need to do this:

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

The argument passed to Collectors.joining is optional.