如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:17:58  来源:igfitidea点击:

How to use stream in Java 8 to collect a couple of fields into one list?

javajava-8java-streamcollectors

提问by user2620644

For example I have class Personwith nameand surnamefields.

例如,我有一个Person带有namesurname字段的类。

I want to collect a Listof String(names and surnames all together) from Listof Person, but it seems that I can't use map twice per one list or can't use stream twice per list.

我想从of收集Listof String(姓名和姓氏全部),但似乎我不能为每个列表使用两次 map 或不能为每个列表使用两次流。ListPerson

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::getSurnamenon-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 nameof the persons. Then you're recreating a stream from this Setand not from your List<Person> persons.

结果是Set<String>只包含namepersons。然后你从这个Set而不是从你的List<Person> persons.

That's why you can not use Person::getSurnameto 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));