diy
diy

Reputation: 3610

Invoke method on property of each bean in collection

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?

Upvotes: 1

Views: 253

Answers (5)

Brian Agnew
Brian Agnew

Reputation: 272297

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.

Upvotes: 1

Esko
Esko

Reputation: 29377

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.

Upvotes: 2

diy
diy

Reputation: 3610

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

Upvotes: 0

danben
danben

Reputation: 83250

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.

Upvotes: 2

Eli Acherkan
Eli Acherkan

Reputation: 6411

I believe the JDK collections framework doesn't have anything more elegant than the iteration solution.

Upvotes: 0

Related Questions