Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve array[] of values from ArrayList of objects

Tags:

java

arrays

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.

like image 480
Stevoisiak Avatar asked Dec 04 '25 14:12

Stevoisiak


1 Answers

Create a target array of the same size as the list then iterate through the list and add each element's age to the target array.

like image 50
Lew Bloch Avatar answered Dec 06 '25 03:12

Lew Bloch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!