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?
Two options:
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]);
java 8:
String[] names = Arrays.asStream(people).map(Person::getName).asArray(String[]::new);
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.