Sonnenhut Sonnenhut - 1 year ago 102
Java Question

Get list of attributes of an object in an List

When there is an

, is there a possibility of getting List of all
out of that?
Is there an prepared call for that, or do I have to write an foreach loop like:

List<Person> personList = new ArrayList<Person>();
List<String> namesList = new ArrayList<String>();
for(Person person : personList){

Answer Source

Java 8 and above:

List<String> namesList =

If you need to make sure you get an ArrayList as a result, you have to change the last line to:


Java 7 and below:

The standard collection API prior to Java 8 has no support for such transformation. You'll have to write a loop (or wrap it in some "map" function of your own), unless you turn to some fancier collection API / extension.

(The lines in your Java snippet are exactly the lines I would use.)

In Apache Commons, you could use CollectionUtils.collect and a Transformer

In Guava, you could use the Lists.transform method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download