Rakesh Juyal
Rakesh Juyal

Reputation: 36799

How to change the value of an attribute of a bean in list?

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.

Upvotes: 1

Views: 807

Answers (2)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299208

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)

Upvotes: 1

Riduidel
Riduidel

Reputation: 22308

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.

Upvotes: 2

Related Questions