如何在 Java 8 中使用流将几个字段收集到一个列表中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42028143/
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
How to use stream in Java 8 to collect a couple of fields into one list?
提问by user2620644
For example I have class Person
with nameand surnamefields.
例如,我有一个Person
带有name和surname字段的类。
I want to collect a List
of String
(names and surnames all together) from List
of Person
, but it seems that I can't use map twice per one list or can't use stream twice per list.
我想从of收集List
of String
(姓名和姓氏全部),但似乎我不能为每个列表使用两次 map 或不能为每个列表使用两次流。List
Person
My code is:
我的代码是:
persons.stream()
.map(Person::getName)
.collect(Collectors.toSet())
.stream().map(Person::getSurname)
.collect(Collectors.toList())
but it keeps telling me that Person::getSurname
non-static method can't be referenced from static context.
但它一直告诉我Person::getSurname
不能从静态上下文中引用非静态方法。
What am I doing wrong?
我究竟做错了什么?
回答by Landei
To get both names and surnames in the same list, you could do this:
要在同一个列表中同时获取姓名和姓氏,您可以执行以下操作:
List<String> set = persons.stream()
.flatMap(p -> Stream.of(p.getName(),p.getSurname()))
.collect(Collectors.toList());
回答by Matthieu Saleta
When you're doing :
当你在做:
persons.stream().map(Person::getName).collect(Collectors.toSet())
The result is a Set<String>
that contains only the name
of the persons
.
Then you're recreating a stream from this Set
and not from your List<Person> persons
.
结果是Set<String>
只包含name
的persons
。然后你从这个Set
而不是从你的List<Person> persons
.
That's why you can not use Person::getSurname
to map this Set
.
这就是为什么你不能Person::getSurname
用来映射 this Set
。
The solution from @Alexis C. :
persons.stream().flatMap(p -> Stream.of(p.getName(), p.getSurname()).collect(Collectors.toSet())
must do the job.
@Alexis C. 的解决方案:
persons.stream().flatMap(p -> Stream.of(p.getName(), p.getSurname()).collect(Collectors.toSet())
必须完成这项工作。
回答by matejetz
Your code should look something like that:
你的代码应该是这样的:
persons.stream()
.map(person -> person.getName() + " " + person.getSurname)
.collect(Collectors.toList());
回答by Jayen Chondigara
if person has first name and middle name optional then use below code
如果人的名字和中间名是可选的,则使用下面的代码
return Stream.of(Optional.ofNullable(person)
.map(Person::getFirstName)
.orElse(null),
Optional.ofNullable(person)
.map(Person::getMiddleName)
.orElse(null))
.filter(Objects::nonNull)
.collect(Collectors.joining(SPACE));