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.
创建与列表大小相同的目标数组,然后遍历列表并将每个元素的age
添加到目标数组。
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();
}
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.