Update specific object items in array list Java

I want to ask a question, how do I update the records in the array list object:

For example:

List<User> userList = new ArrayList<User>();

User user = new User();
user.setUserId(1);
user.setUsername("user1");
userList.add(user);

User user = new User();
user.setUserId(2);
user.setUsername("user2");
userList.add(user);

User user = new User();
user.setUserId(3);
user.setUsername("user3");
userList.add(user);

Now I want to update a specific record in my array list. Suppose I want to update the user name of the user ID #2, for example:

User user = new User();
user.setUserId(2);
user.setUsername("new_username2");

//before i want to remove or update the record on the list which contain user id #2
userList.add(user);

Like I want to search userlist from the list Contains (2) then delete or update it with the new value

Thank you in advance

Solution

In your case, I think it's better to use map instead of list:

Map<Integer,User> userMap = new HashMap<Integer,User>();

User user = new User();
user.setUserId(1);
user.setUsername("user1");
userMap.put(user.getUserId(),user);

user = new User();
user.setUserId(2);
user.setUsername("user2");
userMap.put(user.getUserId(),user);

user = new User();
user.setUserId(3);
user.setUsername("user3");
userMap.put(user.getUserId(),user);

In this way, you can directly search for the required userid:

User userToModify = userMap.remove(idToModify);
userToModify.setUsername("new name");
userToModify.setUserId(54);
userMap.put(user.getUserId(),userToModify);

If you only need to find objects through one field (userid in this case), the map is more efficient and easy to use (and maintainable)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>