Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate a string with the new 1.8 stream API [duplicate]

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?

like image 559
ZeDonDino Avatar asked Jun 23 '16 09:06

ZeDonDino


People also ask

How do I concatenate a stream?

Stream. concat() method creates a concatenated stream in which the elements are all the elements of the first stream followed by all the elements of the second stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel. The calls to Stream.

What are the 2 methods used for string concatenation?

There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.


1 Answers

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.

like image 184
Thomas Betous Avatar answered Sep 26 '22 21:09

Thomas Betous