Collectors method summarizingLong() in Java
A Collectors static method summarizingLong() used to produce a summary statistics for each long type input element using mapping function. It returns summary statistics for the resulting values.
Syntax
 1 public static <T> Collector<T,?,LongSummaryStatistics> summarizingLong(ToLongFunction<? super T> mapper)
T : It represents a data type of the input elements.
mapper : It is a mapping function that will be applied to each element.
return : It returns a Collector that implements the summary-statistics reduction.
Collectors method summarizingLong()
 1 package com.java;
 2 
 3 import java.util.Arrays;
 4 import java.util.List;
 5 import java.util.LongSummaryStatistics;
 6 import java.util.stream.Collectors;
 7 
 8 public class Main {
 9 
 10     public static void main(String[] args) {
 11 
 12         List<Long> list = Arrays.asList(102L, 20L, 30L, 40L, 25L);
 13 
 14         LongSummaryStatistics res = list.stream().collect(
 15                 Collectors.summarizingLong(val -> val * 2));
 16 
 17         System.out.println("A summarized result is : " + res);
 18     }
 19 }
In the above example, a list of long is created by passing an long values. A list elements are stream using stream() method that collected by collect() method. It creates a summary of elements by multiplying each value by 2. It returns an instance of LongSummaryStatistics that includes count, sum, min, average, and max value. The result is assigned to the variable that will be printed.
Output
 1 A summarized result is : LongSummaryStatistics{count=5, sum=434, min=40, average=86.800000, max=204}

sumarizingLong() with custom object

sumarizingLong() with custom object
 1 package com.java;
 2 
 3 import java.util.*;
 4 import java.util.stream.Collectors;
 5 
 6 public class Example {
 7     public static void main(String[] args) {
 8 
 9         Employee emp1 = new Employee("Emp1","Tech",  12000);
 10         Employee emp2 = new Employee("Emp2","Admin", 31000);
 11         Employee emp3 = new Employee("Emp3","Admin", 21000);
 12         Employee emp4 = new Employee("Emp4","Tech",  41000);
 13         Employee emp5 = new Employee("Emp5","Tech",  37000);
 14 
 15         List<Employee> employees = Arrays.asList(emp1, emp2, emp3, emp4, emp5);
 16 
 17         LongSummaryStatistics res = employees.stream().collect(
 18                 Collectors.summarizingLong(Employee::getSalary));
 19 
 20         System.out.println("Mapped employee object : " + res);
 21     }
 22 }
In the above example, a summarizingLong() method called by passing a an Employee class instance method reference getSalary(). It creates a summary object of employee salary and returns that result.
Output
 1 Sumarrized employee salary : LongSummaryStatistics{count=5, sum=142000, min=12000, average=28400.000000, max=41000}
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us