Ninad Pingale
Ninad Pingale

Reputation: 7079

Read property of objects in array

I have a array of objects. When I print it, it looks like :

[com.groups.bean.User@5a2045, com.groups.bean.User@fcabd6, com.groups.bean.User@758cdb]

I want array of values of its property "Name" like :

[John,Mike,Peter]

I know, I can iterate through the array and call property "Name" of each object and put it in a new array.

But I want to avoid looping. Is there any shortcut for it ?

Upvotes: 0

Views: 75

Answers (2)

aga
aga

Reputation: 29434

You can override toString() method in your User object:

public class User {
    private String name;

    @Override
    public String toString() {
        return this.name;
    }
}

You can write it w/o @Override, though. Here you can find documentation on this annotation.

Upvotes: 5

grexter89
grexter89

Reputation: 1102

Override the toString() method of User.

Upvotes: 2

Related Questions