tags:

views:

44

answers:

2

I am having a list of bean, now i want to change the value of an attribute of all the beans in the list. For example:

class Person{
    String name;
    int age;
    String attrXYZ;

    /* accessors and mutators */
}

List<Person> lstPerson = getAllPersons();
//set the attribute attrXYZ of all persons in the list to 'undefined'

One way is to iterate the list and call setAttrXYZ ( 'undefined' ); this is what i am doing right now.
I would like to know is there any other approach of doing this.

+2  A: 

Unfortunatly, even using reflection, you would have to iterate over your list. As a consequence, as far as I know, there is no other solution to that.

Riduidel
Unfortunately, i have to accept this.
Rakesh Juyal
+1  A: 

This is the advantage of dynamic languages like groovy, where you could do this as a one-liner:

myList.each{ it.setAttrXYZ ( 'undefined' ) }

In java, the shortest way is either to use java 5 loops or iterators:

for(MyBean bean : list){
    bean.setAttrXYZ ( "undefined" );
}

or

Iterator<MyBean> it = list.iterator();
while(it.hasNext()){
    it.next().setAttrXYZ("undefined");
}

(both of which is pretty much the same thing internally)

seanizer
No matter the amount of syntactic sugar or dynamic code you throw at it, it still is just a simple loop over the list applying some code to each element.
Joachim Sauer
internally, yes. But for the developer it can be a question of: "do I really want to go through all this trouble?" vs. "hey, not a problem". (Not in this trivial case of course)
seanizer
woa, i like that one liner groovy code[ even if it is not in java ] :)
Rakesh Juyal