Search code examples
javaarraylistiteratorlistiterator

Java - How to iterate through an objects arraylist and adding elements that meet a certain condition to another objects arraylist


I have a class UserGroup which has an ArrayList userList. I make a 1st instance of the class called 'myUserGroup' and fill it with 10 elements then i make a 2nd called 'administrators'. I want to iterate through the 'myUserGroup' arraylist and if the element is equal to "admin" add it to the 'administrators' arraylist.

Here's the UserGroup class:

public class UserGroup {

    ArrayList<User> userList;

    UserGroup(){
        userList = new ArrayList<User>();

    public Iterator<User> getUserIterator() {
        Iterator<User> iterate = userList.iterator();
        return iterate;
    }

Here's the class in which i'm trying to add the elements to the 2nd UserGroup arraylist:

public class Main {

public static void main(String[] args) {

    UserGroup myUserGroup = new UserGroup();

    myUserGroup.addSampleData();

    UserGroup administrators = new UserGroup();

    while(myUserGroup.getUserIterator().hasNext()) {

        if(myUserGroup.getUserIterator().next().getUserType().equals("admin")) {

            administrators.userList.add(myUserGroup.getUserIterator().next());
        }
    }

Solution

  • A couple problems:

    1. I think you're getting a new iterator on each loop.
    2. You call next() twice when you intend to get the same object, getting two subsequent objects.

    Try this instead of your while loop:

    for (User u : myUserGroup.userList) {
      if (u.getUserType().equals("admin")) {
        administrators.userList.add(u);
      }
    }