1

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?

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

4 Comments

I tried with list.add() but its only adding the last value.
You need to iterate (for example with a for loop) if you need to add many values or you need to use addAll. add(E e) adds an element (only one)
when I use addAll() I get the reference value. Not the Client Names.
addAll add all the elements of a collection. If you need to add the client names I show you how to do
2

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());

1 Comment

Public support for 1.5 ended on Oct 2009, premier support ended on May 2011, and extended support ended on May 2015. Seriously consider upgrading.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.