Summarizing methods in Java 8

  • Last Updated: May 4, 2024
  • By: javahandson
  • Series
img

Summarizing methods in Java 8

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

 

Summarizing methods

Java 8 Stream API Collectors class has a set of summarizing methods that include operations for generating summary statistics on the collection of numbers.

Summarizing is designed to collect statistics such as count, sum, min, max, and average for a stream of objects. Summarizing is extremely beneficial when we want to compute the above statistics together as it avoids the need for multiple passes over the data.

We don’t have to calculate the sum, min, max, and average of numbers individually because all these operations will be done in one go using the summarizing methods. It is a powerful tool for data analysis, allowing us to extract useful insights from the collections of objects.

Variants of summarizing methods

There are 3 variants of summarizing methods.

  1. summarizingInt method
  2. summarizingLong method
  3. summarizingDouble method

We will learn about these methods with examples in the below section.

summarizingInt method

summarizingInt is used to calculate summary statistics for a stream of objects using an integer-valued property.

Syntax:

public static <T> Collector<T, ?, IntSummaryStatistics> summarizingInt(ToIntFunction<? super T> mapper> mapper)

Method Signature Explained:

a. <T>: This is a generic type parameter that represents the type of elements in the stream.

b. Collector<T, ?, IntSummaryStatistics>: This describes the return type of the method:

  • It returns a Collector that processes elements of type T.
  • The result of the collector is an IntSummaryStatistics object that holds the computed summary statistics. This summary statistics includes operations like count, sum, min, max, and average, of the int values extracted from the elements of the stream.

c. ToIntFunction<? super T> mapper: This is the functional interface parameter that specifies how to transform the elements of the stream into int values. The mapper function takes an element of type T (or any of its super types) and returns an int value. This int value is then used to compute the summary statistics.

Write a program to calculate the statistics on marks for all the students.

package com.javahands.collectors.summarizing;
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.summarizing;

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

public class SummarizingInt {
    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));

        IntSummaryStatistics marksStats = studentList.stream()
                .collect(Collectors.summarizingInt(Student::getMarks));

        System.out.println("Average marks: " + marksStats.getAverage());
        System.out.println("Total marks: " + marksStats.getSum());
        System.out.println("Maximum marks: " + marksStats.getMax());
        System.out.println("Minimum marks: " + marksStats.getMin());
        System.out.println("Number of marks: " + marksStats.getCount());
    }
}
Output:
Average marks: 436.6666666666667
Total marks: 2620
Maximum marks: 490
Minimum marks: 380
Number of marks: 6

summarizingLong method

The summarizingLong method acts the same as the summarizingInt method but the difference is, that this method is designed for collecting statistics from a stream of objects based on a long value. This method can be used where the values might exceed the maximum limit of the integer.

Syntax:

public static <T> Collector<T, ?, LongSummaryStatistics> summarizingLong(ToLongFunction<? super T>mapper)

Method Signature Explained:

a. <T>: This is a generic type parameter that represents the type of elements in the stream.

b. Collector<T, ?, LongSummaryStatistics>: This describes the return type of the method:

  • It returns a Collector that processes elements of type T.
  • The result of the collector is a LongSummaryStatistics object that holds the computed summary statistics. This summary statistics includes operations like count, sum, min, max, and average, of the long values extracted from the elements of the stream.

c. ToLongFunction<? super T> mapper: This is the functional interface parameter that specifies how to transform the elements of the stream into long values. The mapper function takes an element of type T (or any of its super types) and returns a long value. This long value is then used to compute the summary statistics.

Write a program to calculate the statistics on a long datatype.

package com.javahands.collectors.summarizing;
public class Product {

    long productId;
    String productName;
    double price;

    public Product(long productId, String productName, double price) {
        super();
        this.productId = productId;
        this.productName = productName;
        this.price = price;
    }

    public long getProductId() {
        return productId;
    }

    public void setProductId(long productId) {
        this.productId = productId;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}
package com.javahands.collectors.summarizing;

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

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

        List<Product> products = Arrays.asList(
                new Product(101l, "Wheat", 155.50),
                new Product(102l, "Rice", 255.00),
                new Product(103l, "Cooking Oil", 525.70),
                new Product(104l, "Cookies", 200.00),
                new Product(105l, "Beans", 150.50));

        LongSummaryStatistics longSummaryStatistics = products.stream()
                .collect(Collectors.summarizingLong(Product::getProductId));

        System.out.println(longSummaryStatistics);
    }
}
Output: LongSummaryStatistics{count=5, sum=515, min=101, average=103.000000, max=105}

summarizingDouble method

The summarizingDouble method acts the same as summarizingInt and summarizingLong method but the difference is, that this method is designed for collecting statistics from a stream of objects based on a double value. This method can be used when we are dealing with precision values.

Syntax:

public static <T> Collector<T, ?, DoubleSummaryStatistics> summarizingDouble(ToDoubleFunction<? super T> mapper)

Method Signature Explained:

a. <T>: This is a generic type parameter that represents the type of elements in the stream.

b. Collector<T, ?, DoubleSummaryStatistics>: This describes the return type of the method:

  • It returns a Collector that processes elements of type T.
  • The result of the collector is a DoubleSummaryStatistics object that holds the computed summary statistics. This summary statistics includes operations like count, sum, min, max, and average, of the double values extracted from the elements of the stream.

c. ToDoubleFunction mapper: This is the functional interface parameter that specifies how to transform the elements of the stream into double values. The mapper function takes an element of type T (or any of its super types) and returns a double value. This double value is then used to compute the summary statistics.

Write a program to calculate the statistics on a double datatype.

package com.javahands.collectors.summarizing;

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

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

        List<Product> products = Arrays.asList(
                new Product(101l, "Wheat", 155.50),
                new Product(102l, "Rice", 255.00),
                new Product(103l, "Cooking Oil", 525.70),
                new Product(104l, "Cookies", 200.00),
                new Product(105l, "Beans", 150.50));

        DoubleSummaryStatistics doubleSummaryStatistics = products.stream()
                .collect(Collectors.summarizingDouble(Product::getPrice));

        System.out.println(doubleSummaryStatistics);
    }
}
Output: DoubleSummaryStatistics{count=5, sum=1286.700000, min=150.500000, average=257.340000, max=525.700000}

So this is all about the summarizing methods in 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