Sobes.tech
Junior

What are summarizingLong and LongSummaryStatistics?

sobes.tech AI

Answer from AI

summarizingLong is a method in Dart (part of the collection package or standard libraries) that allows collecting statistics on a collection of long type numbers (in Dart, this is int).

LongSummaryStatistics is a class that stores aggregated data: the number of elements, sum, minimum and maximum values, as well as the average.

Example of usage in Dart:

import 'dart:math';

void main() {
  List<int> numbers = [10, 20, 30, 40, 50];

  var stats = numbers.fold(
    LongSummaryStatistics(),
    (LongSummaryStatistics acc, int value) => acc.accept(value),
  );

  print('Count: ${stats.count}');
  print('Sum: ${stats.sum}');
  print('Min: ${stats.min}');
  print('Max: ${stats.max}');
  print('Average: ${stats.average}');
}

class LongSummaryStatistics {
  int count = 0;
  int sum = 0;
  int? min;
  int? max;

  LongSummaryStatistics accept(int value) {
    count++;
    sum += value;
    min = (min == null || value < min!) ? value : min;
    max = (max == null || value > max!) ? value : max;
    return this;
  }

  double get average => count == 0 ? 0 : sum / count;
}

Thus, summarizingLong helps quickly obtain basic statistical indicators for a set of numbers.