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

12,319

Solution 1

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

Solution 2

java 8:

String[] names = Arrays.asStream(people).map(Person::getName).asArray(String[]::new);
Share:
12,319

Related videos on Youtube

Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    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?

    • markspace
      markspace almost 7 years
      Pretty much you have to iterate. You can use streams but for small lists they are not efficient.
    • matfax
      matfax almost 7 years
      You are using an imperative language. Therefore, explicit iterations are the way to go. If you don't like writing loops, go with a functional language such as Scala. There you could use a simple one-liner and have it.
    • jmrah
      jmrah almost 7 years
      @MatthiasFax, I agree with you that the streaming API is built around the core language and not from the bottom up, but it does allow you to use functional idioms, and therefore, not have to explicit iterate. The 'explicit iterating' was the only point I was addressing.
  • Andreas
    Andreas almost 7 years
    Since OP would accept List as result type ("For example, to create an array or list of just names or hair color"), a for-each loop adding to a List<String> would be another nice option to show, for completeness, i.e. for (Person p : people) { names.add(p.name); }
  • m_callens
    m_callens almost 7 years
    @Andreas ah yup! I was gunna do a List<String> initially but didn't notice that in the question