Java 8 lambda create list of Strings from list of objects

依然范特西╮ 提交于 2020-02-13 04:55:32

问题


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());

回答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 aswell be written as user -> user.getAdress() (because the type User will be inferred by the compiler)




回答2:


One more way of using lambda collectors like above answers

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



回答3:


It is extended your idea:

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


来源:https://stackoverflow.com/questions/51747704/java-8-lambda-create-list-of-strings-from-list-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!