Join a list of object's properties into a String

winhell :

I'm learning lambda right now, and I wonder how can I write this code by a single line with lambda.

I have a Person class which includes an ID and name fields

Currently, I have a List<Person> which stores these Person objects. What I want to accomplish is to get a string consisting of person's id just like.

"id1,id2,id3".

How can I accomplish this with lambda?

Ousmane D. :

To retrieve a String consisting of all the ID's separated by the delimiter "," you first have to map the Person ID's into a new stream which you can then apply Collectors.joining on.

String result = personList.stream().map(Person::getId)
                          .collect(Collectors.joining(","));

if your ID field is not a String but rather an int or some other primitive numeric type then you should use the solution below:

String result = personList.stream().map(p -> String.valueOf(p.getId()))
                          .collect(Collectors.joining(","));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=427982&siteId=1