Search code examples
javaarraysoopobject

Java - Easiest way to get single property from each object in a list/array?


Say I have a person object with properties such as name, hair color, and eye color. I have the following array Person[] people that contains instances of person objects.

I know I can get the name property of one the Person objects with

// create a new instance of Person
Person george = new Person('george','brown','blue');
// <<< make a people array that contains the george instance here... >>>
// access the name property
String georgesName = people[0].name;

But what if I want to access the name property of everyone without using indexes? For example, to create an array or list of just names or hair color? Do I have to manually iterate through my people array? Or is there something cool in Java like String[] peopleNames = people.name?


Solution

  • Two options:

    1. Iteration
    2. Streams (Java 8)

    Iteration

    List<String> names = new ArrayList<>();
    for (Person p : people) {
        names.add(p.name);
    }
    

    Streams

    String[] names = Arrays.stream(people).map(p -> p.name).toArray(size -> new String[people.length]);