47

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());
2
  • 7
    You're almost there. Assuming your map lambda returns a String just add .collect(Collectors.toList()) to map(...). Commented Aug 8, 2018 at 13:15
  • 3
    Note: (User user) -> user.getAddress() can be written as user -> user.getAddress() or just User::getAddress Commented Aug 8, 2018 at 13:24

4 Answers 4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Starting with Java 16, one can use just .toList() instead of .collect(Collectors.toList()).
9

It is extended your idea:

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

1 Comment

You should add a new answer if its better/ alternative than the other one. Explain how its better.
4

One more way of using lambda collectors like above answers

 List<String> tmpAdresses= users
                  .stream()
                  .collect(Collectors.mapping(User::getAddress, Collectors.toList()));

Comments

-3

You can use this to convert Long to String:

List<String> ids = allListIDs.stream()
                             .map(listid-> String.valueOf(listid))
                             .collect(Collectors.toList());

1 Comment

This doesn't attempt to answer the OPs question, though. OP is explicitly asking to map a User to its adress. Also how is your question different to the already existing ones?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.