Get a {@link Collector} that calculates the <code>AVG()</code> for any
type of {@link Number}.
770863
@SuppressWarnings({ "rawtypes", "unchecked" })
    public static <T, U> Collector<T, ?, Optional<U>> avg(Function<? super T, ? extends U> function) {
        return Collector.of(
            () -> (Sum<U>[]) new Sum[1],
            (s, v) -> {
                if (s[0] == null)
                    s[0] = Sum.create(function.apply(v));
                else
                    s[0].add(function.apply(v));
            },
            (s1, s2) -> {
                s1[0].add(s2[0]);
                return s1;
            },
            s -> s[0] == null ? Optional.empty() : Optional.of(s[0].avg())
        );
    }
925380
public static <T, U> Collector<T, ?, Seq<U>> maxAll(Function<? super T, ? extends U> function, Comparator<? super U> comparator) {
        return collectingAndThen(maxAllBy(function, comparator), t -> t.map(function));
    }
226554
public static double median(FlatDataCollection flatDataCollection) {
        double[] doubleArray = flatDataCollection.stream().filter(x -> x!=null).mapToDouble(TypeInference::toDouble).toArray();
        int n = doubleArray.length;
        if(n==0) {
            throw new IllegalArgumentException("The provided collection can't be empty.");
        }
        Arrays.sort(doubleArray);
        
        double median;
        if(n%2==0) {
            median = (doubleArray[n/2 - 1] + doubleArray[n/2])/2.0;
        }
        else {
            median = doubleArray[n/2];
        }
        
        return median;
    }
409007
@Override
    public double average()
    {
        readLock.lock();
        try
        {
            int count = count();
            double s = 0;
            double c = 0;
            PrimitiveIterator.OfInt it = modIterator();
            while (it.hasNext())
            {
                int m = it.nextInt();
                s += sin[m];
                c += cos[m];
            };
            return toDegrees(s / count, c / count);
        }
        finally
        {
            readLock.unlock();
        }
    }
856471
public void collectStats(final StatsCollector collector) {
    final byte[][] kinds = {
        METRICS_QUAL.getBytes(CHARSET),
        TAG_NAME_QUAL.getBytes(CHARSET),
        TAG_VALUE_QUAL.getBytes(CHARSET)
      };
    try {
      final Map<String, Long> used_uids = UniqueId.getUsedUIDs(this, kinds)
        .joinUninterruptibly();

      collectUidStats(metrics, collector);
      if (config.getBoolean("tsd.core.uid.random_metrics")) {
        collector.record("uid.ids-used", 0, "kind=" + METRICS_QUAL);
        collector.record("uid.ids-available", 0, "kind=" + METRICS_QUAL);
      } else {
        collector.record("uid.ids-used", used_uids.get(METRICS_QUAL),
            "kind=" + METRICS_QUAL);
        collector.record("uid.ids-available",
            (Internal.getMaxUnsignedValueOnBytes(metrics.width()) -
                used_uids.get(METRICS_QUAL)), "kind=" + METRICS_QUAL);
      }

      collectUidStats(tag_names, collector);
      collector.record("uid.ids-used", used_uids.get(TAG_NAME_QUAL),
          "kind=" + TAG_NAME_QUAL);
      collector.record("uid.ids-available",
          (Internal.getMaxUnsignedValueOnBytes(tag_names.width()) -
              used_uids.get(TAG_NAME_QUAL)),
          "kind=" + TAG_NAME_QUAL);

      collectUidStats(tag_values, collector);
      collector.record("uid.ids-used", used_uids.get(TAG_VALUE_QUAL),
          "kind=" + TAG_VALUE_QUAL);
      collector.record("uid.ids-available",
          (Internal.getMaxUnsignedValueOnBytes(tag_values.width()) -
              used_uids.get(TAG_VALUE_QUAL)), "kind=" + TAG_VALUE_QUAL);

    } catch (Exception e) {
      throw new RuntimeException("Shouldn't be here", e);
    }

    collector.record("uid.filter.rejected", rejected_dps.get(), "kind=raw");
    collector.record("uid.filter.rejected", rejected_aggregate_dps.get(),
        "kind=aggregate");

    {
      final Runtime runtime = Runtime.getRuntime();
      collector.record("jvm.ramfree", runtime.freeMemory());
      collector.record("jvm.ramused", runtime.totalMemory());
    }

    collector.addExtraTag("class", "IncomingDataPoints");
    try {
      collector.record("hbase.latency", IncomingDataPoints.putlatency, "method=put");
    } finally {
      collector.clearExtraTag("class");
    }

    collector.addExtraTag("class", "TSDB");
    try {
      collector.record("datapoints.added", datapoints_added, "type=all");
    } finally {
      collector.clearExtraTag("class");
    }

    collector.addExtraTag("class", "TsdbQuery");
    try {
      collector.record("hbase.latency", TsdbQuery.scanlatency, "method=scan");
    } finally {
      collector.clearExtraTag("class");
    }
    final ClientStats stats = client.stats();
    collector.record("hbase.root_lookups", stats.rootLookups());
    collector.record("hbase.meta_lookups",
                     stats.uncontendedMetaLookups(), "type=uncontended");
    collector.record("hbase.meta_lookups",
                     stats.contendedMetaLookups(), "type=contended");
    collector.record("hbase.rpcs",
                     stats.atomicIncrements(), "type=increment");
    collector.record("hbase.rpcs", stats.deletes(), "type=delete");
    collector.record("hbase.rpcs", stats.gets(), "type=get");
    collector.record("hbase.rpcs", stats.puts(), "type=put");
    collector.record("hbase.rpcs", stats.appends(), "type=append");
    collector.record("hbase.rpcs", stats.rowLocks(), "type=rowLock");
    collector.record("hbase.rpcs", stats.scannersOpened(), "type=openScanner");
    collector.record("hbase.rpcs", stats.scans(), "type=scan");
    collector.record("hbase.rpcs.batched", stats.numBatchedRpcSent());
    collector.record("hbase.flushes", stats.flushes());
    collector.record("hbase.connections.created", stats.connectionsCreated());
    collector.record("hbase.connections.idle_closed", stats.idleConnectionsClosed());
    collector.record("hbase.nsre", stats.noSuchRegionExceptions());
    collector.record("hbase.nsre.rpcs_delayed",
                     stats.numRpcDelayedDueToNSRE());
    collector.record("hbase.region_clients.open",
        stats.regionClients());
    collector.record("hbase.region_clients.idle_closed",
        stats.idleConnectionsClosed());

    compactionq.collectStats(collector);
    // Collect Stats from Plugins
    if (startup != null) {
      try {
        collector.addExtraTag("plugin", "startup");
        startup.collectStats(collector);
      } finally {
        collector.clearExtraTag("plugin");
      }
    }
    if (rt_publisher != null) {
      try {
        collector.addExtraTag("plugin", "publish");
        rt_publisher.collectStats(collector);
      } finally {
        collector.clearExtraTag("plugin");
      }
    }
    if (authentication != null) {
      try {
        collector.addExtraTag("plugin", "authentication");
        authentication.collectStats(collector);
      } finally {
        collector.clearExtraTag("plugin");
      }
    }
    if (search != null) {
      try {
        collector.addExtraTag("plugin", "search");
        search.collectStats(collector);
      } finally {
        collector.clearExtraTag("plugin");
      }
    }
    if (storage_exception_handler != null) {
      try {
        collector.addExtraTag("plugin", "storageExceptionHandler");
        storage_exception_handler.collectStats(collector);
      } finally {
        collector.clearExtraTag("plugin");
      }
    }
    if (ts_filter != null) {
      try {
        collector.addExtraTag("plugin", "timeseriesFilter");
        ts_filter.collectStats(collector);
      } finally {
        collector.clearExtraTag("plugin");
      }
    }
    if (uid_filter != null) {
      try {
        collector.addExtraTag("plugin", "uidFilter");
        uid_filter.collectStats(collector);
      } finally {
        collector.clearExtraTag("plugin");
      }
    }
  }
740627
public static <T> Collector<T, ?, Seq<T>> maxAll(Comparator<? super T> comparator) {
        return maxAllBy(t -> t, comparator);
    }
276413
public Statistics columnAvgLength(String columnName, Double avgLen) {
		this.columnStats
			.computeIfAbsent(columnName, column -> new HashMap<>())
			.put(AVG_LENGTH, String.valueOf(avgLen));
		return this;
	}
252835
public static Collector<Link, ?, Links> collector() {
		return Collectors.collectingAndThen(Collectors.toList(), Links::of);
	}
366420
public static <T, U> Collector<T, ?, Long> countDistinctBy(Function<? super T, ? extends U> function) {
        return Collector.of(
            () -> new HashSet<U>(),
            (s, v) -> s.add(function.apply(v)),
            (s1, s2) -> {
                s1.addAll(s2);
                return s1;
            },
            s -> (long) s.size()
        );
    }
636945
public static <T extends Number> double getAverage(Collection<T> values, AVERAGE_TYPE type) {
		switch(type) {
			case ARITHMETIC:
				double sum = 0.0;
				for(T t: values) {
					sum += t.doubleValue();
				}
				return sum/values.size();
			default: throw new IllegalArgumentException("\""+type+"\" is not a valid verage-type!");
		}
	}
561048
public static <T, U> Collector<T, ?, Optional<T>> minBy(Function<? super T, ? extends U> function, Comparator<? super U> comparator) {
        return maxBy(function, comparator.reversed());
    }
534229
public static <T> Collector<T, ?, Optional<T>> percentile(double percentile, Comparator<? super T> comparator) {
        return percentile(percentile, t -> t, comparator);
    }
772162
public static <T, U> Collector<T, ?, Optional<T>> medianBy(Function<? super T, ? extends U> function, Comparator<? super U> comparator) {
        return percentileBy(0.5, function, comparator);
    }
564170
@Override
    public double average()
    {
        readLock.lock();
        try
        {
            double s = 0;
            PrimitiveIterator.OfInt it = modIterator();
            while (it.hasNext())
            {
                s += ring[it.nextInt()];
            }
            return s/(count());
        }
        finally
        {
            readLock.unlock();
        }
    }
312595
public static <T, U extends Comparable<? super U>> Collector<T, ?, Optional<Double>> percentRankBy(U value, Function<? super T, ? extends U> function) {
        return percentRankBy(value, function, naturalOrder());
    }
905403
public static BigDecimal avg(final Iterable<? extends Number> target) {
        Validate.notNull(target, "Cannot aggregate on null");
        Validate.containsNoNulls(target, "Cannot aggregate on array containing nulls");
        BigDecimal total = BigDecimal.ZERO;
        int size = 0;
        for (final Number element : target) {
            total = total.add(toBigDecimal(element));
            size++;
        }
        if (size == 0) {
            return null;
        }
        final BigDecimal divisor = BigDecimal.valueOf(size);
        try {
            return total.divide(divisor);
        } catch (final ArithmeticException e) {
            // We will get an arithmetic exception if: 1. Divisor is zero, which is impossible; or 2. Division
            // returns a number with a non-terminating decimal expansion. In the latter case, we will set the
            // scale manually.
            return total.divide(divisor, Math.max(total.scale(), 10), RoundingMode.HALF_UP);
        }
    }
1204128
public Object getResult(AverageData data) {
        return data.count == 0 ? null : data.total / data.count;
    }