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

257
Views
Retrieve array[] of values from ArrayList of objects

Let's say I have an ArrayList of objects. For example: ArrayList<Person> personList, where each Person has 2 class variables String name and int age. These variables each have their own getter methods getName() and getAge().

What is the simplest way to retrieve an array (or ArrayList) of int ages[]?

Note this question is similar to the verbosely titled "Retrieve an array of values assigned to a particular class member from an array of objects in java", though without the arbitrary restriction on for-loops, and using an ArrayList instead of an Array.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Create a target array of the same size as the list then iterate through the list and add each element's age to the target array.

over 4 years ago · Santiago Trujillo Report

0

Numerous ways to do this -- here is one.

First get the ages into a list (using a java8 stream), and then convert the list into an array.

public int[] getAges() {
    return personList.stream()
        .mapToInt(Person::getAge)
        .toArray();
}
over 4 years ago · Santiago Trujillo Report

0

Person P1 = new Person("Dev", 25);
Person P2 = new Person("Andy", 12);
Person P3 = new Person("Mark", 20);
Person P4 = new Person("Jon", 33);

ArrayList<Person> personList = new ArrayList<>(Arrays.asList(new Person[] { P1, P2, P3, P4 }));
int[] ages = getPersonAges(personList); // [25, 12, 20, 33]

private static int[] getPersonAges(ArrayList<Person> personList) {
    int[] ages = new int[personList.size()];
    int idx = 0;

    for (Person P : personList) {    // Iterate through the personList
        int age = P.getAge();
        ages[idx++] = age;
    }

    return ages;
}
over 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!