我有用户对象列表,我只想根据用户对象中的变量从列表中获取用户对象。
public class User {
private int id;
private String sex;
private int age;
private String country;
/**
* Getter and setter for all variables
*/
}
我有一个这样的模型类。现在我有了用户对象列表。
List<User> users = new ArrayList<User>();
如果用户是男性,我想从用户列表中获取对象。
List<User> ageList = new ArrayList<User>();
for(User object : users) {
if(object.getSex().equals("Male")){
ageList.add(object);
}
}
我不喜欢上面的方法。有没有更好的方法根据对象中的变量从对象列表中获取对象..?
Java Collections 有什么功能吗?我们可以使用 Java Comparator 解决这个问题吗?
最佳答案
如果您使用 Guava , 你可以使用 Collections2.filter
:
Collection<User> males = Collections2.filter(users, new Predicate<User>() {
@Override
public boolean apply(User user) {
return user.getSex().equals("Male");
}
});
使用 Java 8,您可以做得更好:
Collection<User> males = Collections2.filter(users, user -> user.getSex().equals("Male"));
关于java - 根据对象中的变量从对象列表中获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6242276/