Can you collect(joining()) without mapping to string?

守給你的承諾、 提交于 2019-12-01 07:35:08

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/50583490/can-you-collectjoining-without-mapping-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!