Invoke method on property of each bean in collection
Suppose I have a class A with property b
Class A {
public i开发者_高级运维nt 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?
Why don't you think this is elegant? Almost anything shorter would require removing some type information - generally you choose to program in Java because you want to use a strongly- and statically-typed language.
Or maybe because it has tons of libraries and frameworks and lots of Manning books and all your inherited legacy code is in Java. Whatever.
Use LambdaJ:
List<Integer> bees = collect(originalList, on(A).b);
Basically LamdbaJ's idea is to get all the nifty list methods available in functional languages to Java and then it even goes as far as adding it's own version of closures to the whole pile. Definately worth checking out.
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/@b
and it will return a collection of b
. 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.
I believe the JDK collections framework doesn't have anything more elegant than the iteration solution.
I ended up with the following solution
List propertyList = new ArrayList();
CollectionUtils.collect(list,new Transformer() {
@Override
public Object transform(Object input) {
return ((LogMessage)input).getLogRunIds();
}
},propertyList);
Unfortunately, Transform interface doesn't allow using generics, so i have to use explicit casts
Many thakns to Brian Agnew for an insight
精彩评论