Java 8 Lambda从对象列表创建字符串列表 [英] Java 8 lambda create list of Strings from list of objects

查看:529
本文介绍了Java 8 Lambda从对象列表创建字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:

如何将以下代码片段转换为Java 8 lambda样式?

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

推荐答案

您需要collect您的流进入列表:

You need to collect your stream into a List:

List<String> adresses = users.stream()
    .map(User::getAdress)
    .collect(Collectors.toList());

有关其他Collectors的更多信息,请访问

For more information on the different Collectors visit the documentation

User::getAdress只是编写(User user) -> user.getAdress()的另一种形式,也可以写为user -> user.getAdress()(因为类型User将由编译器推断)

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)

这篇关于Java 8 Lambda从对象列表创建字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆