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?
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.
In Java, we can use String. join(",", list) to join a List String with commas.
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(","));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With