2 bbb 5 eee 7 ggg
public class User {
private int id;
private String name = "";
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
List<User> users = new ArrayList<User>();
users.add(new User(1, "aaa"));
users.add(new User(2, "bbb"));
users.add(new User(3, "ccc"));
users.add(new User(4, "ddd"));
users.add(new User(5, "eee"));
users.add(new User(6, "fff"));
users.add(new User(7, "ggg"));
List<Integer> users1= new ArrayList<Integer>();
removeUsers.add(3);
removeUsers.add(6);
removeUsers.add(1);
removeUsers.add(4);
}
}
如果users1
id 3和users
id 3相等,那么我想删除用户中的值并仅打印不匹配的值,如上所示。
答案 0 :(得分:0)
for (User user : users1)
{
if (users.contains(user))
{
users.remove(user);
}
}
这样可行,但前提是您覆盖了User类中的equals()方法。
@Override
public boolean equals(User user)
{
return (id == user.getId());
}
答案 1 :(得分:0)
这是一个非常简单的示例,它避免了ConcurrentModificationException
public class Users
{
private User getUserById(List<User> users, int id)
{
for (User user : users)
{
if (user.getId() == id)
{
return user;
}
}
return null;
}
public void removeUsers()
{
List<User> users = new ArrayList<User>();
users.add(new User(1, "aaa"));
users.add(new User(2, "bbb"));
users.add(new User(3, "ccc"));
users.add(new User(4, "ddd"));
users.add(new User(5, "eee"));
users.add(new User(6, "fff"));
users.add(new User(7, "ggg"));
List<Integer> removeUsers = new ArrayList<Integer>();
removeUsers.add(3);
removeUsers.add(6);
removeUsers.add(1);
removeUsers.add(4);
for (Integer integer : removeUsers)
{
User userToRemove = getUserById(users,integer);
if (userToRemove != null)
{
users.remove(userToRemove);
}
}
for (User user : users)
{
System.out.println(user.getId() + " " + user.getName());
}
}
public static void main(String[] args)
{
Users users = new Users();
users.removeUsers();
}
}
答案 2 :(得分:0)
for (Iterator<User> i = users.iterator(); i.hasNext(); ) {
User user = i.next();
if (users1.contains(user.getId()))
i.remove();
}
for (User u : users)
System.out.println(u.getId() + " " + u.getName());