0

I have a ArrayList<MyDataType> pList; where MyDataType is a simple class like below:

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?

For example

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

I want to know what the right hand side of the above statement should look like.

5 Answers 5

2

Declare a List<String> than iterate over pList and add name to names list.

 List<String> names=new ArrayList<>();
 for(MyDataType dt:pList){
 names.add(dt.getName())
 }
Sign up to request clarification or add additional context in comments.

Comments

0

You're going to need to iterate over pList and add each name one by one.

3 Comments

Hi Winzu, I was thinking the same, but still is there any way to initialize it apart from iterating ?
I don't know any syntax that would do what you want. But there are multiple examples of what you need in the answer now ;)
Thanks for all others who gave me quick replies
0
List<String> names = new ArrayList<String>();

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

Comments

0

There are some functional ways to do this such as Guava, but that comes with some major performance concerns. 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); 
}

Comments

0

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

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.