111

Lets say we have a simple method that should concat all names of a Person collection and return the result string.

public String concantAndReturnNames(final Collection<Person> persons) {
    String result = "";
    for (Person person : persons) {
        result += person.getName();
    }
    return result;
}

Is there a way to write this code with new stream API forEach function in 1 line?

Thomas Betous
  • 4,633
  • 2
  • 24
  • 45
ZeDonDino
  • 5,072
  • 8
  • 27
  • 28
  • Consider renaming to "concatenate a string scalar property on a collection of pojos" (with the new....) Because your question (and the accepted answer) is beyond "a string" IMHO. Upvote for the question and top answer from me today. – granadaCoder Aug 08 '22 at 20:48

1 Answers1

199

The official documentation for what you want to do: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html

 // Accumulate names into a List
 List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());

 // Convert elements to strings and concatenate them, separated by commas
 String joined = things.stream()
                       .map(Object::toString)
                       .collect(Collectors.joining(", "));

For your example, you would need to do this:

 // Convert elements to strings and concatenate them, separated by commas
 String joined = persons.stream()
                       .map(Person::getName) // This will call person.getName()
                       .collect(Collectors.joining(", "));

The argument passed to Collectors.joining is optional.

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
Thomas Betous
  • 4,633
  • 2
  • 24
  • 45