Java 8 lambda 从对象列表创建字符串列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51747704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 lambda create list of Strings from list of objects
提问by LStrike
I have the following qustion:
我有以下问题:
How can I convert the following code snipped to Java 8 lambda style?
如何将截取的以下代码转换为 Java 8 lambda 样式?
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());
采纳答案by Lino
You need to collect
your stream into a List:
您需要将collect
流转换为列表:
List<String> adresses = users.stream()
.map(User::getAdress)
.collect(Collectors.toList());
For more information on the different Collectors
visit the documentation
有关不同Collectors
访问文档的更多信息
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)
User::getAdress
只是另一种写法(User user) -> user.getAdress()
,也可以写成user -> user.getAdress()
(因为User
编译器会推断出类型)
回答by Piotr R
It is extended your idea:
它扩展了你的想法:
List<String> tmpAdresses = users.stream().map(user ->user.getAdress())
.collect(Collectors.toList())
回答by Oomph Fortuity
One more way of using lambda collectors like above answers
使用上述答案的 lambda 收集器的另一种方法
List<String> tmpAdresses= users
.stream()
.collect(Collectors.mapping(User::getAddress, Collectors.toList()));