如何使用Java 8 Stream从某些类属性中获取List? [英] How can I get a List from some class properties with Java 8 Stream?

查看:1291
本文介绍了如何使用Java 8 Stream从某些类属性中获取List?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有列表< Person> 。我需要从 Person 的属性中获取 List

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

例如,我有一个 Person 类:

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<Person> personList = new ArrayList<>();
personList.add(new Person("David"));
personList.add(new Person("Joe"));
personList.add(new Person("Michel"));
personList.add(new Person("Barak"));

我想获得名称列表 Stream 这样的API:

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

List<String> names = personList.stream().somecode().collect(Collectors.toList());
names.stream().forEach(System.out::println);

#David
#Joe
#Michel
#Barak

此代码不起作用:

public class Main 
{
    public static void main(String[] args) 
    {
        List<Person> 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<String> 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<String> friends;

    Person(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }

    public List<String> getFriends() {
        return friends;
    }
}



我怎样才能得到一个带 Stream API的属性的列表


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

推荐答案

这是基本的,你使用 map

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

编辑:

为了结合朋友姓名列表,你需要使用 flatMap

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

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

这篇关于如何使用Java 8 Stream从某些类属性中获取List?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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