Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

259
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda