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

I have a List<Person>. I need to 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<Person> 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 a list of names with the Stream API, like this:

List<String> 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<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;
    }
}


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

This question is related to java collections java-8 java-stream

The answer is


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());

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?

Examples related to java-8

Default interface methods are only supported starting with Android N Class has been compiled by a more recent version of the Java Environment Why is ZoneOffset.UTC != ZoneId.of("UTC")? Modify property value of the objects in list using Java 8 streams How to use if-else logic in Java 8 stream forEach Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit What are functional interfaces used for in Java 8? java.time.format.DateTimeParseException: Text could not be parsed at index 21 Java 8 lambda get and remove element from list

Examples related to java-stream

Sorting a list with stream.sorted() in Java Modify property value of the objects in list using Java 8 streams How to use if-else logic in Java 8 stream forEach Java 8 lambda get and remove element from list Create list of object from another using Java 8 Streams Java 8 Stream API to find Unique Object matching a property value Reverse a comparator in Java 8 Ignore duplicates when producing map using streams Modifying Objects within stream in Java8 while iterating How can I get a List from some class properties with Java 8 Stream?