简体   繁体   中英

Map two ArrayList with different sizes

For Example:

ArrayList1 = {userid1, userid2, userid1, userid4, userid1, userid3, userid2, userid4, userid4, userid4, userid2};

ArrayList2 = {username1, username2, username3, username4};

Mapping these two array so that whenever I call ArrayList1.get(0).getUserName() , it should provide me with username1 .

public class User {
        String username;

        public User(String username)
        {
            this.username = username;
        }
        /**
         * @return the username
         */
        public String getUsername() {
            return username;
        }

        /**
         * @param username the username to set
         */
        public void setUsername(String username) {
            this.username = username;
        }
    }

userid1, userid2 ... must be User objects

User userid1 = new User("username1");    
User userid2 = new User("username2");   

Initialize all the user objects

ArrayList1 = {userid1, userid2, userid1, userid4, userid1, userid3, userid2, userid4, userid4, userid4, userid2};

Then you can call

   String username =  ArrayList1.get(0).getUserName();

this will return username1

I think you should use :

List<List<T>> = ArrayList<ArrayList<T>>;

T is the class of you UserName.

There is a better way to do that and that is by using HashMap :

//create your custom object which will be mapped
public class User{
  public String userId;
  public String userName;
}


ArrayList<String> userKeys = new ArrayList<String>();
HashMap<String, User> users = new HashMap<String, User>();

Now using a userKey, you can access its corresponding userData;

Example:

User user = users.get("yourKey");

Use HashSet instead of arraylist. Set does not allow duplicate.

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