java 类中list属性,如何使用Java 8 Stream从某些类属性中获取List?

I have a List. I need get a List from a property of Person.

For example, I have a Person class:

class Person

{

private String name;

private String birthDate;

public String getName() {

return name;

}

public String getBirthDate() {

return birthDate;

}

Person(String name) {

this.name = name;

}

}

List personList = new ArrayList<>();

personList.add(new Person("David"));

personList.add(new Person("Joe"));

personList.add(new Person("Michel"));

personList.add(new Person("Barak"));

I want to get list of names with Stream API like this:

List names = personList.stream().somecode().collect(Collectors.toList());

names.stream().forEach(System.out::println);

#David

#Joe

#Michel

#Barak

This code doesn't work:

public class Main

{

public static void main(String[] args)

{

List personList = new ArrayList<>();

Person person = new Person("Иван");

person.getFriends().addAll(Arrays.asList("Друг 1", "Друг 2", "Друг 3"));

personList.add(person);

person = new Person("Федор");

person.getFriends().addAll(Arrays.asList("Друг 4", "Друг 5", "Друг 6"));

personList.add(person);

person = new Person("Алексей");

person.getFriends().addAll(Arrays.asList("Друг 7", "Друг 8", "Друг 9"));

personList.add(person);

person = new Person("Константин");

person.getFriends().addAll(Arrays.asList("Друг 10", "Друг 11", "Друг 12"));

List friens = personList.stream().map(e->e.getFriends()).collect(Collectors.toList());

friends.stream().forEach(System.out::println);

//Друг 1

//Друг 2

//Друг 3

//Друг 4

//...

}

}

class Person

{

String name;

List friends;

Person(String name) {

this.name = name;

}

public String getName() {

return name;

}

public List getFriends() {

return friends;

}

}

How can I get a List of a property with Stream API?

解决方案

That's basic, you use map :

List names =

personList.stream()

.map(Person::getName)

.collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List friendNames =

personList.stream()

.flatMap(e->e.getFriends().stream())

.collect(Collectors.toList());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值