我正在阅读java 8 in action,作者说如果你有一个重写toString方法的类,那么在执行collect(joining())时不需要将流映射到字符串。一个例子:
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);
}
但是,这不起作用,只能这样:
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<CharSequence, ?, String> joining()
显然这不能像Person
那样工作不是 CharSequence
的实例.
关于java - 您可以在不映射到字符串的情况下收集(joining())吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50583490/