Reputation: 513
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
Reputation: 26926
Generally to add values to a List
(so also to an ArrayList
) you can use the methods:
add(E e)
to add an element at the end of the listadd(int index, E element)
to add an element in the specified positionaddAll(Collection<? extends E> c)
to add all the element at the end of the listaddAll(int index, Collection<? extends E> c)
to add all the element starting from a specified positionPlease 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
Reputation: 41
Like you get the Clientnames one by one, you can fill up your list one by one
Upvotes: 1
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