Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of attributes of an object in an List

When there is an List<Person>, is there a possibility of getting List of all person.getName() 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){     namesList.add(personList.getName()); } 
like image 973
Sonnenhut Avatar asked Sep 05 '11 14:09

Sonnenhut


People also ask

How do I see all the attributes of an object in Python?

Use Python's vars() to Print an Object's Attributes The dir() function, as shown above, prints all of the attributes of a Python object.

How do you print the attributes of an object in Python?

To print the attributes of an object we can use “object. __dict__” and it return a dictionary of all names and attributes of object. After writing the above code (python print object attributes), once you will print “x. __dict__” then the output will appear.


1 Answers

Java 8 and above:

List<String> namesList = personList.stream()                                    .map(Person::getName)                                    .collect(Collectors.toList()); 

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

                                    ...                                     .collect(Collectors.toCollection(ArrayList::new)); 

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.

like image 55
aioobe Avatar answered Sep 22 '22 08:09

aioobe