I have List of User object, I just want to get User objects from List based on variables in User object.
public class User {
private int id;
private String sex;
private int age;
private String country;
/**
* Getter and setter for all variables
*/
}
I have a model class like this. Now I have list of User objects.
List<User> users = new ArrayList<User>();
I want to get the objects from users list if the user is Male.
List<User> ageList = new ArrayList<User>();
for(User object : users) {
if(object.getSex().equals("Male")){
ageList.add(object);
}
}
I do not like the above approach. Is there any better way to get objects from List of objects based on variable in object..?
Is there any functions Java Collections ..? can we solve this using Java Comparator..?
If you’re using Guava, you can use
Collections2.filter:And with Java 8, you can do even better: