How do I sum object property using Stream API?

If you have a collection of objects and want to sum one of their properties using the Java Stream API, you need to use the map() function to convert each object into the value of its property and then use the reduce() function to sum all the values.

Here is an example where we have a Person class with age property, and we want to get the sum of ages for a list of Person objects:

package org.kodejava.basic;

public class Person {
    private final int age;

    // Constructor, getters, and setters...
    public Person(int age) {
        this.age = age;
    }

    public int getAge() {
        return this.age;
    }
}
package org.kodejava.basic;

import java.util.Arrays;
import java.util.List;

public class PropertySumDemo {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person(20),
                new Person(30),
                new Person(40));

        int totalAge = people.stream()
                .mapToInt(Person::getAge)
                .sum();

        System.out.println(totalAge);  // Outputs: 90
    }
}

In this example, mapToInt(Person::getAge) converts each Person object in the people stream into an int representing their age. The sum() function then adds up these ages, resulting in the total age.

How do I use min, max, avg and sum Projections?

The code below demonstration the use of Projections.min(), Projections.max(), Projections.avg() and Projections.sum().

package org.kodejava.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.HibernateException;
import org.hibernate.Criteria;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Projections;
import org.kodejava.hibernate.model.Track;

public class MinMaxAvgSumProjectionsDemo {
    public static Session getSession() throws HibernateException {
        String cfg = "hibernate.cfg.xml";
        SessionFactory sessionFactory = new Configuration().configure(cfg)
                .buildSessionFactory();
        return sessionFactory.openSession();
    }

    public static void main(String[] args) {
        try (Session session = getSession()) {
            Criteria criteria = session.createCriteria(Track.class)
                    .setProjection(Projections.max("duration"));
            Integer maxDuration = (Integer) criteria.uniqueResult();
            System.out.println("Max Track Duration = " + maxDuration);

            criteria.setProjection(Projections.min("duration"));
            Integer minDuration = (Integer) criteria.uniqueResult();
            System.out.println("Min Track Duration = " + minDuration);

            criteria.setProjection(Projections.avg("duration"));
            Double avgDuration = (Double) criteria.uniqueResult();
            System.out.println("Avg Track Duration = " + avgDuration);

            criteria.setProjection(Projections.sum("duration"));
            Long totalDuration = (Long) criteria.uniqueResult();
            System.out.println("Total Track Duration = " + totalDuration);
        }
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

Maven Central Maven Central