Sam
Sam

Reputation: 513

How to add number of String values to an ArrayList?

I have a scenario wherein I have a Bean class from where I'm getting all the Client names and other Client related details. I'm creating a Bean object and getting all the details.

ArrayList<ClientBean> clientList = (ArrayList<ClientBean>) (new QueriesDAO())
                .getAllClient();

From the above code I am getting all the details of the Client. And to get only the Client names I'm through the index form,

ClientBean clist = clientList.get(2);   
        for (ClientBean clientBean : clientList) {
        clientBean.getclientName(); // here I'm getting only the Client names one by one.   
        }   

My Question is How do I add only the Client names in an ArrayList dynamically?

Upvotes: 1

Views: 76

Answers (3)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

Generally to add values to a List (so also to an ArrayList) you can use the methods:

Please check the documentation (linked on the answer) for details on each method.


To add all client names to a list (I assumed that a name is a String, eventually change the type)

List<String> names = new ArrayList<String>();
for (ClientBean clientBean : clientList) {
    names.add(clientBean.getclientName());
}
// Here names is a list with all the requested names

Upvotes: 3

vnc
vnc

Reputation: 41

Like you get the Clientnames one by one, you can fill up your list one by one

Upvotes: 1

Justin Kaufman
Justin Kaufman

Reputation: 261

Consider using Java 8's Lambda features. Based on your post it sounds like this is what you're looking for.

List<ClientBean> allClients = new QueriesDAO().getAllClients();
List<String> allClientsNames = allClients.stream()
                                         .map(ClientBean::getClientName)
                                         .collect(Collectors.toList());

Upvotes: 2

Related Questions