java8 stream concatenate map output to string return java.util.stream.ReferencePipeline

Viewed 496

Hi I'd like to extract and format attributes from object steam and concatenate them in a new string.

Ex

public class User{
   public User(String name, String lastname){
      this.name = name;
      this.lastname = lastname;
   }
   public String name;
   public String lastname;
}


List<User> memberNames = new ArrayList<>();
memberNames.add(new User("john", "rush");
memberNames.add(new User("peter", "gabriel");

String users = "";

users += memberNames.stream().map(user ->{return String.format("The user name is %s and his lastname is %s\n", user.name, user.lastname); });

but when i try to print users string

logger.info(users);

I obtain

java.util.stream.ReferencePipeline$3@396555a1

instead of

The user name is john and his lastname is rush
The user name is peter and his lastname is gabriel

Thanks in advance

1 Answers
java.util.stream.ReferencePipeline$3@396555a1

is the outcome of trying to print the Stream you have created until the map operation performed.

You are looking to collect the user names mapped until now while joining then with a \n delimiter.

String users = memberNames.stream()
        .map(user -> String.format("The user name is %s and his lastname is %s", user.name, user.lastname))
        .collect(Collectors.joining("\n"));
System.out.println(users); // to print them all at once
Related