Summing method in Collectors API

  • Last Updated: April 11, 2024
  • By: javahandson
  • Series
img

Summing method in Collectors API

In this article, we will try to understand the summing method in the Collectors API of Java 8. We will also learn about different variants of this method with examples.

 

Java 8 Collectors class has a set of summing methods that include operations for summing numerical values on the stream of objects.

Summing Methods

Summing methods are used to perform the sum operations on a certain property i.e. a variable from a stream of objects. This property can be of integer, long, or double type.

There are 3 variants of summing methods that are discussed below.

summingInt method

This method is used to sum the integer values of a certain property from a stream of objects. Say we have a collection of custom objects that holds an integer property, then using the summingInt method we can perform the addition operation on that property.

Ex. We have a list of Students and the Student object has an integer property named marks then we can use the summingInt method to sum up the marks of all the students in the list.

Syntax

static <T> Collector<T,?,Integer> summingInt(ToIntFunction<? super T> mapper)

Parameter:

mapper - It is a ToIntFunction interface. This interface is used for lambda expressions or method references that produce an int value from an object of type T.

Write a program to add the marks of all students in the list.

package com.javahands.collectors.summing;

public class Student {

    int rollNumber;
    String name;
    int marks;

    public Student(int rollNumber, String name, int marks) {
        this.rollNumber = rollNumber;
        this.name = name;
        this.marks = marks;
    }

    public int getMarks() {
        return marks;
    }
}
package com.javahands.collectors.summing;

import java.util.List;
import java.util.stream.Collectors;

public class SummingEx {
    public static void main(String[] args) {

        List<Student> studentList = Arrays.asList(
                new Student(101, "Suraj", 450),
                new Student(102, "Iqbal", 470),
                new Student(103, "Amar", 430),
                new Student(104, "Amit", 400),
                new Student(105, "Suchit", 380),
                new Student(106, "Kartik", 490)
        );

        int totalMarks = studentList.stream()
                .collect(Collectors.summingInt(Student::getMarks));
        System.out.println("Total marks of students : "+totalMarks);
    }
}
Output: Total marks of students : 2620

In the above example, summingInt method adds marks of all the students from the student list. If no elements are present in the student list then the result is 0.

package com.javahands.collectors.summing;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class SummingEx {
    public static void main(String[] args) {

        List<Student> studentList = new ArrayList<>();

        int totalMarks = studentList.stream()
                .collect(Collectors.summingInt(Student::getMarks));
        System.out.println("Total marks of students : "+totalMarks);
    }
}
Output: Total marks of students : 0

summingLong method

The summingLong method behaves the same way as summingInt method but the difference is summingLong method sums up the long values and returns a long result.

This method can also be used to sum the int elements due to implicit type conversion in Java. This means that if we have a collection of objects with an int property, we can still use summingLong to sum those int values and Java will automatically convert the int values to long. This feature is useful if we are adding a large set of integer elements as it can overcome the risk of overflow if the result of addition exceeds the Maximum integer value.

Syntax

static <T> Collector<T,?,Long> summingLong(ToLongFunction<? super T> mapper)

Parameter:

mapper - It is a ToLongFunction interface. This interface is used for lambda expressions or method references that produce an long value from an object of type T.

summingDouble method

The summingDouble method also behaves the same as the summingInt and summingLong methods but the difference is summingDouble method sums up the double values and returns a double result.

Syntax

static <T> Collector<T,?,Double> summingDouble(ToDoubleFunction<? super T> mapper)

Parameter:

mapper - It is a ToDoubleFunction interface. This interface is used for lambda expressions or method references that produce an double value from an object of type T.

The summingDouble method in Java’s Collectors class can take an argument as an int, long, or any other numeric type. These numeric types will be automatically converted to double types.

This conversion allows you to sum integer values as double values, which can be particularly useful when you need the summing operation to have the precision or range of a double.

package com.javahands.collectors.summing;

class LargeNumbers {

    int number;

    LargeNumbers(int number) {
        this.number = number;
    }

    public int getNumber() {
        return number;
    }
}
package com.javahands.collectors.summing;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class SummingEx {

    public static void main(String[] args) {

        List<LargeNumbers> list = Arrays.asList(
                new LargeNumbers(2147483647),
                new LargeNumbers(10)
        );

        int intSum = list.stream()
                .collect(Collectors.summingInt(LargeNumbers::getNumber));

        System.out.println("Sum fails as intSum exceeds the max int limit : "+intSum);

        long longSum = list.stream()
                .collect(Collectors.summingLong(LargeNumbers::getNumber));

        System.out.println("Sum success as the value gets converted to long type : "+longSum);

        double doubleSum = list.stream()
                .collect(Collectors.summingDouble(LargeNumbers::getNumber));

        System.out.println("Sum success as the value gets converted to double type : "+doubleSum);
    }
}
Output:
Sum fails as intSum exceeds the max int limit : -2147483639
Sum success as the value gets converted to long type : 2147483657
Sum success as the value gets converted to double type : 2.147483657E9 ( 2.147483657 * 10 ^ 9 = 2147483657 )

So this is all about the summing method in Collectors API of Java 8. If you have any questions on this topic, please raise them in the comments section. If you liked this article then please share this post with your friends and colleagues.

Leave a Comment