Reputation: 2531
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):
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.
When every object is supposed to inherit toString
from Object
?
Upvotes: 2
Views: 565
Reputation: 120858
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()
will generate a Stream<People>
, while Collectors.joining
has a definition of:
public static Collector<CharSequence, ?, String> joining()
obviously this can't work as Person
is not an instance of CharSequence
.
Upvotes: 7