Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

366
Views
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?

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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]);
about 4 years ago · Santiago Trujillo Report

0

java 8:

String[] names = Arrays.asStream(people).map(Person::getName).asArray(String[]::new);
about 4 years ago · Santiago Trujillo Report

0

You are seeking a functional feature in an initially imperative-only language Java. As already mentioned in other answers, since Java 8, you also have functional elements (e.g., streams). However, they are not yet recommended to be used. This blog post explains the disadvantages of streams over loops (i.e., performance, readability, maintainability).

If you are looking for functional and safe code without such major implications, try Scala:

case class Person(name: String)
val persons = Array(Person("george"), Person("michael"), Person("dexter"))
val personNames = persons.map(_.name)

The main difference is that this Scala code is simple to read and it is comparably performant as a Java code that uses a loop because the translated Scala-to-Java code uses a while loop internally.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!