Java实现:取出泛型为user的list全部username=张三的,并将结果的id取出来组成list,没有加入id组成List的对象将其组成新的userList
时间: 2024-02-18 11:00:44 浏览: 55
Java 实现泛型List
好的,下面是 Java 实现的解决方案:
```java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// 假设您有一个名为userList的列表,其中包含多个User对象
List<User> userList = new ArrayList<>();
userList.add(new User(1, "张三"));
userList.add(new User(2, "李四"));
userList.add(new User(3, "张三"));
userList.add(new User(4, "王五"));
userList.add(new User(5, "张三"));
// 取出泛型为user的list全部username=张三的,并将结果的id取出来组成list:
List<Integer> idList = new ArrayList<>();
List<User> newUserList = new ArrayList<>();
for (User user : userList) {
if (user.getUsername().equals("张三")) {
idList.add(user.getId());
} else {
newUserList.add(user);
}
}
System.out.println(idList); // 输出结果为 [1, 3, 5]
System.out.println(newUserList); // 输出结果为 [User{id=2, username='李四'}, User{id=4, username='王五'}]
}
}
class User {
private int id;
private String username;
public User(int id, String username) {
this.id = id;
this.username = username;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
'}';
}
}
```
希望这个 Java 实现的解决方案能够帮到您!
阅读全文