Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join a list of object's properties into a String

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?

like image 248
winhell Avatar asked May 29 '17 15:05

winhell


People also ask

Can you have a list of objects in Java?

Since List is an interface, objects cannot be created of the type list. We always need a class that implements this List in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the List.

How do you join a list into a string in Java?

In Java, we can use String. join(",", list) to join a List String with commas.


2 Answers

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(",")); 
like image 138
Ousmane D. Avatar answered Sep 20 '22 14:09

Ousmane D.


stream to map, and collect to list!

List<String> myListofPersons = personList.stream()           .map(Person::getId)           .collect(Collectors.toList()); 

if you need that in a String object then join the list

String res = String.join(" , ", myListStringId); System.out.println(res); 
like image 23
ΦXocę 웃 Пepeúpa ツ Avatar answered Sep 18 '22 14:09

ΦXocę 웃 Пepeúpa ツ