Java - Easiest way to get single property from each object in a list/array?
12,319
Solution 1
Two options:
- Iteration
- 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]);
Solution 2
java 8:
String[] names = Arrays.asStream(people).map(Person::getName).asArray(String[]::new);
Related videos on Youtube
Author by
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
Say I have a person object with properties such as
name
,hair color
, andeye color
. I have the following arrayPerson[] people
that contains instances of person objects.I know I can get the
name
property of one thePerson
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 mypeople
array? Or is there something cool in Java likeString[] peopleNames = people.name
?-
markspace almost 7 yearsPretty much you have to iterate. You can use streams but for small lists they are not efficient.
-
matfax almost 7 yearsYou are using an imperative language. Therefore, explicit iterations are the way to go. If you don't like writing loops, go with a functional language such as Scala. There you could use a simple one-liner and have it.
-
jmrah almost 7 years@MatthiasFax, I agree with you that the streaming API is built around the core language and not from the bottom up, but it does allow you to use functional idioms, and therefore, not have to explicit iterate. The 'explicit iterating' was the only point I was addressing.
-
-
Andreas almost 7 yearsSince OP would accept
List
as result type ("For example, to create an array or list of just names or hair color"), a for-each loop adding to aList<String>
would be another nice option to show, for completeness, i.e.for (Person p : people) { names.add(p.name); }
-
m_callens almost 7 years@Andreas ah yup! I was gunna do a
List<String>
initially but didn't notice that in the question