-4

I have a custom object defined here:

public class ContactObject {

    public String contactName;
    public String contactNo;
    public String image;
    public boolean selected;

    public String getName() {
        return contactName;
    }

    public void setName(String contactName) {
        this.contactName = contactName;
    }

    public String getNumber() {
        return contactNo;
    }

    public void setNumber(String contactNo) {
        this.contactNo = contactNo;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

}

And I have populated an ArrayList of this custom object (binderContacts) but now I want to convert this to a normal ArrayList with a list of all the contactNo's in my array list. Can someone help here?

public class ContactsListClass {

    public static final ArrayList<ContactObject> phoneList = new ArrayList<ContactObject>();
    public static final ArrayList<ContactObject> binderContacts = new ArrayList<ContactObject>();
}
Riley MacDonald
  • 453
  • 1
  • 4
  • 15
  • Your title doesn't make much sense. ArrayList which stores elements of some type is still ArrayList. Please correct it to better describe what you want to achieve. – Pshemo Jan 03 '16 at 20:24
  • Also fields in ContactObject class should most probably be private, not public. – Pshemo Jan 03 '16 at 20:25
  • Another thing is that you should prefer to [program on interfaces](http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) rather then its specific implementation. So your `phoneList` and `binderContacts` should be of type `List`, not `ArrayList`. This will give you more flexibility in case you would want to use other list than ArrayList. – Pshemo Jan 03 '16 at 20:29
  • I edited the title - this is probably why I can't find the answer (because I am confused about arraylists/objects in general at the moment). What I want to do is take from the ArrayList binderContacts and convert it to an ArrayList with just phone numbers – Riley MacDonald Jan 03 '16 at 20:31
  • 1
    Create empty ArrayList, iterate over your already filled ArrayList and for each ContactObject read its contactNo and add it to that new ArrayList. – Pshemo Jan 03 '16 at 20:37

2 Answers2

0

Assuming you're using Java 8:

ArrayList<String> contactNos = binderContacts.stream().map(contact -> contact.getNumber()).collect(Collectors.toList());
Rudi Angela
  • 1,463
  • 1
  • 12
  • 20
0
List<String> contactNos = new ArrayList<String>();
for (ContactObject o : phoneList) {
    contactNos.add(o.getNumber());
}
TomaszRykala
  • 927
  • 6
  • 16
  • 33