Home » Java » How to get a single object from a list of Objects in Java

How to get a single object from a list of Objects in Java

Posted by: admin June 30, 2018 Leave a comment

Questions:

I have List of User object, I just want to get a Collect object from List based on variables in User object.

public class User {

    private int id;

    private String sex;

    private int year;

   private int value;

    /**
     * Getter and setter for all variables
     */
}

I have a model class like this. Now I have a list of User objects.

List<User> users = new ArrayList<User>();

I want to create a single object which contains the sum of all the values fro monthly salary

List<Collect> objList = new ArrayList<Collect>();
for(User object : users) {
    if(object.getyear().equals("2013")){
        ageList.add(object);
    }
}

but I am not sure how it will work. As there might be multiple entries in for the same year and I want to sum all the values for the same year and put into the collect object

is there any way where I can create a single object from the list of object and also perform a sum operation based on the same year from the list of object. Also, don’t want to hardcode 2013 for checking year.

Answers: