Java 8 lambda create list of Strings from list of objects
61,831
Solution 1
You need to collect
your Stream
into a List
:
List<String> adresses = users.stream()
.map(User::getAdress)
.collect(Collectors.toList());
For more information on the different Collectors
visit the documentation.
User::getAdress
is just another form of writing (User user) -> user.getAdress()
which could as well be written as user -> user.getAdress()
(because the type User
will be inferred by the compiler)
Solution 2
It is extended your idea:
List<String> tmpAdresses = users.stream().map(user ->user.getAdress())
.collect(Collectors.toList())
Solution 3
One more way of using lambda collectors like above answers
List<String> tmpAdresses= users
.stream()
.collect(Collectors.mapping(User::getAddress, Collectors.toList()));
Comments
-
LStrike over 3 years
I have the following qustion:
How can I convert the following code snipped to Java 8 lambda style?
List<String> tmpAdresses = new ArrayList<String>(); for (User user : users) { tmpAdresses.add(user.getAdress()); }
Have no idea and started with the following:
List<String> tmpAdresses = users.stream().map((User user) -> user.getAdress());
-
Shubhendu Pramanik almost 6 yearsYou should add a new answer if its better/ alternative than the other one. Explain how its better.
-
Gaurav Khandelwal almost 4 yearsThis was indeed helpful to get it from List<Map>, thanks.
-
Lino over 3 yearsThis doesn't attempt to answer the OPs question, though. OP is explicitly asking to map a
User
to itsadress
. Also how is your question different to the already existing ones?