假设我们有一个简单的方法,它应该连接 Person 集合的所有名称并返回结果字符串。
public String concantAndReturnNames(final Collection<Person> persons) {
String result = "";
for (Person person : persons) {
result += person.getName();
}
return result;
}
有没有办法在 1 行中使用新的流 API forEach 函数编写此代码?
您想要执行的操作的官方文档:https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html 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
是可选的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)