Question

Java 8 lambda create list of Strings from list of custom class objects

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());
 46  116562  46
1 Jan 1970

Solution

 104

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)

2018-08-08

Solution

 9

It is extended your idea:

List<String> tmpAdresses = users.stream().map(user ->user.getAdress())
.collect(Collectors.toList())
2018-08-08