简体   繁体   English

如何从用户数据类型的ArrayList创建字符串的ArrayList

[英]How to create a ArrayList of strings from a ArrayList of user data type

I have a ArrayList<MyDataType> pList; 我有一个ArrayList<MyDataType> pList; where MyDataType is a simple class like below: 其中MyDataType是一个简单的类,如下所示:

class MyDataType {
    int modified;
    String name;
}

If my pList has size of 10 and if i want to retrieve ArrayList of names for all objects in it, how do I do that? 如果我的pList大小为10,并且我想检索其中所有对象的名称ArrayList,我该怎么做?

For example 例如

ArrayList<String> myNames = new ArrayList<pList...>();

I want to know what the right hand side of the above statement should look like. 我想知道上面陈述的右侧应该是什么样子。

Declare a List<String> than iterate over pList and add name to names list . 声明List<String>不是遍历pList并将name添加到names list

 List<String> names=new ArrayList<>();
 for(MyDataType dt:pList){
 names.add(dt.getName())
 }

您将需要迭代pList并逐个添加每个名称。

List<String> names = new ArrayList<String>();

for(int i = 0; i < pList.size(); i++)
{
    names.add(pList.get(i).getName());
}

you can do like this 你可以这样做

List<MyDataType > pList=new ArrayList<MyDataType >();

List<String> myNames = new ArrayList<String>();
for (MyDataType myDataType : pList) {           
    myNames.add(myDataType.getName());      
}

There are some functional ways to do this such as Guava, but that comes with some major performance concerns. 有一些功能性方法可以实现这一点,例如Guava,但这会带来一些主要的性能问题。 Stick to the basics and iterate through the list. 坚持基础并迭代列表。

List<String> names = new ArrayList<String>();
for(MyDataType element:pList){
    //hopefully this would use an accessor element.getName()
    names.add(element.name); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM