Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

367
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

java 8:

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

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda