Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get objects from List of objects based on variable in object

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..?

like image 474
arulraj.net Avatar asked Jun 05 '11 10:06

arulraj.net


1 Answers

If you're using Guava, you can use Collections2.filter:

Collection<User> males = Collections2.filter(users, new Predicate<User>() {
    @Override
    public boolean apply(User user) {
        return user.getSex().equals("Male");
    }
});

And with Java 8, you can do even better:

Collection<User> males = Collections2.filter(users, user -> user.getSex().equals("Male"));
like image 105
Chris Jester-Young Avatar answered Oct 15 '22 16:10

Chris Jester-Young