How can I get a List from some class properties with Java 8 Stream?

前端 未结 1 1620
我在风中等你
我在风中等你 2020-11-28 02:18

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

For example, I have a Person class:<

相关标签:
1条回答
  • 2020-11-28 02:31

    You can use map :

    List<String> 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<String> friendNames = 
        personList.stream()
                  .flatMap(e->e.getFriends().stream())
                  .collect(Collectors.toList());
    
    0 讨论(0)
提交回复
热议问题