如何将多个字符串值添加到 ArrayList?
How to add number of String values to an ArrayList?
我有一个场景,其中我有一个 Bean class,我从那里获取所有客户名称和其他与客户相关的详细信息。我正在创建一个 Bean 对象并获取所有详细信息。
ArrayList<ClientBean> clientList = (ArrayList<ClientBean>) (new QueriesDAO())
.getAllClient();
从上面的代码中,我得到了客户端的所有详细信息。并通过索引表仅获取客户名称,
ClientBean clist = clientList.get(2);
for (ClientBean clientBean : clientList) {
clientBean.getclientName(); // here I'm getting only the Client names one by one.
}
我的问题是如何在 ArrayList 中动态添加客户端名称?
通常要将值添加到 List
(也可以添加到 ArrayList
),您可以使用以下方法:
add(E e)
在列表末尾添加一个元素
add(int index, E element)
在指定位置添加一个元素
addAll(Collection<? extends E> c)
添加列表末尾的所有元素
addAll(int index, Collection<? extends E> c)
添加从指定位置开始的所有元素
请查看文档(链接在答案中)以了解每种方法的详细信息。
将所有客户端名称添加到列表中(我假设一个名称是String
,最终更改类型)
List<String> names = new ArrayList<String>();
for (ClientBean clientBean : clientList) {
names.add(clientBean.getclientName());
}
// Here names is a list with all the requested names
考虑使用 Java 8 的 Lambda 功能。根据您的 post,这听起来像是您要找的东西。
List<ClientBean> allClients = new QueriesDAO().getAllClients();
List<String> allClientsNames = allClients.stream()
.map(ClientBean::getClientName)
.collect(Collectors.toList());
就像您一个一个地获取客户名称一样,您可以一个一个地填写您的列表
我有一个场景,其中我有一个 Bean class,我从那里获取所有客户名称和其他与客户相关的详细信息。我正在创建一个 Bean 对象并获取所有详细信息。
ArrayList<ClientBean> clientList = (ArrayList<ClientBean>) (new QueriesDAO())
.getAllClient();
从上面的代码中,我得到了客户端的所有详细信息。并通过索引表仅获取客户名称,
ClientBean clist = clientList.get(2);
for (ClientBean clientBean : clientList) {
clientBean.getclientName(); // here I'm getting only the Client names one by one.
}
我的问题是如何在 ArrayList 中动态添加客户端名称?
通常要将值添加到 List
(也可以添加到 ArrayList
),您可以使用以下方法:
add(E e)
在列表末尾添加一个元素add(int index, E element)
在指定位置添加一个元素addAll(Collection<? extends E> c)
添加列表末尾的所有元素addAll(int index, Collection<? extends E> c)
添加从指定位置开始的所有元素
请查看文档(链接在答案中)以了解每种方法的详细信息。
将所有客户端名称添加到列表中(我假设一个名称是String
,最终更改类型)
List<String> names = new ArrayList<String>();
for (ClientBean clientBean : clientList) {
names.add(clientBean.getclientName());
}
// Here names is a list with all the requested names
考虑使用 Java 8 的 Lambda 功能。根据您的 post,这听起来像是您要找的东西。
List<ClientBean> allClients = new QueriesDAO().getAllClients();
List<String> allClientsNames = allClients.stream()
.map(ClientBean::getClientName)
.collect(Collectors.toList());
就像您一个一个地获取客户名称一样,您可以一个一个地填写您的列表