Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
collectors

What is Collectors.summingDouble() in Java?

abhilash

What is the Collectors class?

Collectors is a utility class that provides various implementations of reduction operations such as grouping elements, collecting elements to different collections, summarizing elements according to various criteria, etc. The different functions in the Collectors class are usually used as the final operations in streams.

summingDouble() method

summingDouble() is a static method of the Collectors class that is used to return a Collector. The Collector calculates the sum of the result returned by the implementation of the ToDoubleFunction to the input elements. If there are no elements, zero is returned.

The summingDouble method is defined in the Collectors class. The Collectors class is defined in the java.util.stream package. To import the Collectors class, use the following import statement:

import java.util.stream.Collectors;

Syntax


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

Parameters

  • ToDoubleFunction<? super T> mapper: The function to extract the property or attribute that is to be summed.

Return value

This method returns the sum of the elements which are returned from the ToDoubleFunction implementation.

Code

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

public class Main {

    public static void main(String[] args)
    {
        List<Double> doubleList = Arrays.asList(23.43, 23.32, 8.76567);

        System.out.println("Contents of the list - " + doubleList);

        Stream<Double> doubleStream = doubleList.stream();

        double sumOfElements = doubleStream.collect(Collectors.summingDouble(e -> e));

        System.out.println("Sum of the stream - " + sumOfElements);
    }
}
Implementation of the "summingDouble" method

Explanation

  • Lines 1-4: We import the relevant packages.

  • Line 10: We define a list of type Double called doubleList.

  • Line 12: We print the doubleList.

  • Line 14: We create a stream out of the doubleList.

  • Line 16: We find the sum of the elements of the doubleList using the summingDouble method. Here, the passed ToDoubleFunction implementation returns the passed element itself.

  • Line 18: We print the sum of the elements of the stream.

RELATED TAGS

java
communitycreator
collectors
RELATED COURSES

View all Courses

Keep Exploring