你可以收集(加入())而不映射到字符串吗? [英] Can you collect(joining()) without mapping to string?
问题描述
我正在阅读java 8,并且作者说如果你有一个覆盖toString方法的类,那么在进行collect(joined())时你不需要将流映射到字符串。例如:
I am reading java 8 in action, and the author says that if you have a class that overrides the toString method, you don't need to map the stream to Strings when doing collect(joining()). An example:
public static void main(String... args) {
List<Person> people =
Arrays.asList(
new Person(23, "Paul"),
new Person(23, "John"),
new Person(23, "Greg"),
new Person(24, "Greg"),
new Person(25, "Paul")
); // Person overrides toString
String peopleString = people
.stream()
.collect(Collectors.joining());
System.out.println(peopleString);
}
然而,这不起作用,只有这样:
However, this doesn't work, and only this:
String peopleString = people
.stream()
.map(Person::toString)
.collect(Collectors.joining());
有效,所以这本书错了吗?此外,为什么他说(我改变了一点措辞):
works, so the book is wrong then? Besides, why does he say (I changed the wording a little):
还要注意,如果一个类有一个toString方法返回一个字符串,您将获得相同的结果,而无需使用提取名称的函数映射原始流。
Also note that if a class had a toString method returning a string, you’d obtain the same result without needing to map over the original stream with a function extracting the name.
当每个对象都是应该从对象
继承 toString
?
When every object is supposed to inherit toString
from Object
?
推荐答案
无论这本书说错了,你的解释是对的(除非这一点完全不同而且你没有得到它)
Whatever the book says is wrong and your interpretation is right (unless the point is entirely different and you did not get it)
people.stream()
将生成 Stream< People>
,而 Collectors.joining
的定义为:
public static Collector<CharSequence, ?, String> joining()
显然这不能用作人
不是 CharSequence
的实例。
obviously this can't work as Person
is not an instance of CharSequence
.
这篇关于你可以收集(加入())而不映射到字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!