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

372
Vistas
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?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

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

0

java 8:

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

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.

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