我正在阅读java 8,并且作者说如果你有一个覆盖toString方法的类,那么在进行collect(joined())时你不需要将流映射到字符串.一个例子:
public static void main(String... args) {
List 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);
}
但是,这不起作用,只有这样:
String peopleString = people
.stream()
.map(Person::toString)
.collect(Collectors.joining());
工作,所以这本书错了吗?此外,为什么他说(我改变了一点措辞):
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.
当每个对象都应该从Object继承toString?
解决方法:
无论这本书说错了,你的解释是对的(除非这一点完全不同,你没有得到它)
people.stream()
将生成Stream< People>,而Collectors.joining的定义为:
public static Collector joining()
显然这不能用,因为Person不是CharSequence的实例.
标签:java,java-8,java-stream
来源: https://codeday.me/bug/20191008/1874382.html