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());
}
You will have to loop through and access each objects
getName()
.Maybe guava can do something fancy ...
Try this
Use apache commons collection api.
I think you will always need to do that. But if you will always need such things, then I would suggest to make another class, for example call it
People
wherepersonList
is a variable.Something like this:
In this case you will need to call one getter only each time.
take a look at http://code.google.com/p/lambdaj/ - there is LINQ equivalent for Java. Using it won't avoid iterating all over items but the code would be more compressed.
Java 8 and above:
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 aTransformer
In Guava, you could use the
Lists.transform
method.Not tested but this is the idea: