Suppose I have a class A with property b
Class A {
public int b;
}
There is a collection that containes instances of class A
ArrayList col
How can I get an array of all values of property b from col?
Is there a way more elegant than iteration through col and getting property of each object and then passign values of b to array?
LIst<Integer> propertyValues = new ArrayList<Integer>();
for (A a : col){
propertyValues.add(a.b);
}
Maybe a Spring utility method or something like that?
I think you’re stuck with the above.
Perhaps Commons Collections may give you something more acceptable. See the CollectionUtils class, and in particular the collect() and forAllDo() methods.
Alternatively, JXPath can do this for you (it provides XPath-like navigation over Java beans). You can specify an expression such as
/A/@band it will return a collection ofb. It’s a little excessive if you’re doing this once, but if you’re iterating and navigating over collections it’s a very concise way of doing this.EDIT: As I pointed out in a comment below, Scala will do this in a much more concise form. If you’re running on the JVM and doing a lot of collection work like the above, you may want to check it out.