简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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