java.util.LongSummaryStatistics Java Examples

The following examples show how to use java.util.LongSummaryStatistics. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NumericStreams.java    From Java-11-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
private static void summary() {

        IntSummaryStatistics iss = IntStream.empty().summaryStatistics();
        System.out.println(iss);  //IntSummaryStatistics{count=0, sum=0, min=2147483647, average=0.000000, max=-2147483648}
        iss = IntStream.range(1, 3).summaryStatistics();
        System.out.println(iss);  //IntSummaryStatistics{count=2, sum=3, min=1, average=1.500000, max=2}

        LongSummaryStatistics lss = LongStream.empty().summaryStatistics();
        System.out.println(lss);  //LongSummaryStatistics{count=0, sum=0, min=9223372036854775807, average=0.000000, max=-9223372036854775808}
        lss = LongStream.range(1, 3).summaryStatistics();
        System.out.println(lss);  //LongSummaryStatistics{count=2, sum=3, min=1, average=1.500000, max=2}

        DoubleSummaryStatistics dss = DoubleStream.empty().summaryStatistics();
        System.out.println(dss);  //DoubleSummaryStatistics{count=0, sum=0.000000, min=Infinity, average=0.000000, max=-Infinity}
        dss = DoubleStream.of(1, 2).summaryStatistics();
        System.out.println(dss);  //DoubleSummaryStatistics{count=2, sum=3.000000, min=1.000000, average=1.500000, max=2.000000}

        System.out.println(Integer.MAX_VALUE);  //prints:  2147483647
        System.out.println(Integer.MIN_VALUE);  //prints: -2147483648
        System.out.println(Long.MAX_VALUE);  //prints:  9223372036854775807
        System.out.println(Long.MIN_VALUE);  //prints: -9223372036854775808
        System.out.println(Double.MAX_VALUE);  //prints: 1.7976931348623157E308
        System.out.println(Double.MIN_VALUE);  //prints: 4.9E-324
    }
 
Example #2
Source File: WADFlow.java    From wad with MIT License 6 votes vote down vote up
String statisticsSummary() {
    LongSummaryStatistics warSizeStatistics = this.copier.warSizeStatistics();
    long maxKb = warSizeStatistics.getMax();
    long minKb = warSizeStatistics.getMin();
    long totalKb = warSizeStatistics.getSum();
    String warStats = String.format("WAR sizes: min %d kB, max %d kB, total %d kB\n", minKb, maxKb, totalKb);

    LongSummaryStatistics buildTimeStatistics = this.buildTimeStatistics();
    long maxTime = buildTimeStatistics.getMax();
    long minTime = buildTimeStatistics.getMin();
    long totalTime = buildTimeStatistics.getSum();
    String buildTimeStats = String.format("Build times: min %d ms, max %d ms, total %d ms\n", minTime, maxTime, totalTime);

    String failureStats;
    long failedBuilds = buildErrorCounter.get();
    if (failedBuilds == 0) {
        failureStats = "Great! Every build was a success!";
    } else {
        failureStats = String.format("%d builds failed", buildErrorCounter.get());
    }
    return warStats + buildTimeStats + failureStats;
}
 
Example #3
Source File: LongSummaryStatisticsExample.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void long_summary_stats_with_stream() {

	LongSummaryStatistics stats = shipments.stream()
			.mapToLong((x) -> x.getCost()).summaryStatistics();

	// average
	assertEquals(310.25, stats.getAverage(), 0);

	// count
	assertEquals(4, stats.getCount(), 0);

	// max
	assertEquals(901.0, stats.getMax(), 0);

	// min
	assertEquals(45.0, stats.getMin(), 0);

	// sum
	assertEquals(1241.0, stats.getSum(), 0);
}
 
Example #4
Source File: TestUtils.java    From cubedb with GNU General Public License v3.0 6 votes vote down vote up
public static void ensureSidesAddUp(Map<GroupedSearchResultRow, Long> result) {
  Map<String, LongSummaryStatistics> sideTotals =
      result
      .entrySet()
      .stream()
      .collect(
          Collectors.groupingBy(
              e -> e.getKey().getFieldName(),
              Collectors.summarizingLong(e -> e.getValue().longValue())));
  int numDistinctValues =
      sideTotals
      .values()
      .stream()
      .map(LongSummaryStatistics::getSum)
      .distinct()
      .collect(Collectors.toList())
      .size();
  if (numDistinctValues != 1) {
    log.error("Sides do not add up");
    sideTotals.entrySet().forEach(e -> log.info("{}: {}", e.getKey(), e.getValue().getSum()));
  }
  assertEquals(1, numDistinctValues);
}
 
Example #5
Source File: CollectAndSummaryStatisticsTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public void testLongStatistics() {
    List<LongSummaryStatistics> instances = new ArrayList<>();
    instances.add(countTo(1000).stream().collect(Collectors.summarizingLong(i -> i)));
    instances.add(countTo(1000).stream().mapToLong(i -> i).summaryStatistics());
    instances.add(countTo(1000).stream().mapToLong(i -> i).collect(LongSummaryStatistics::new,
                                                                   LongSummaryStatistics::accept,
                                                                   LongSummaryStatistics::combine));
    instances.add(countTo(1000).parallelStream().collect(Collectors.summarizingLong(i -> i)));
    instances.add(countTo(1000).parallelStream().mapToLong(i -> i).summaryStatistics());
    instances.add(countTo(1000).parallelStream().mapToLong(i -> i).collect(LongSummaryStatistics::new,
                                                                           LongSummaryStatistics::accept,
                                                                           LongSummaryStatistics::combine));

    for (LongSummaryStatistics stats : instances) {
        assertEquals(stats.getCount(), 1000);
        assertEquals(stats.getSum(), (long) countTo(1000).stream().mapToInt(i -> i).sum());
        assertEquals(stats.getAverage(), (double) stats.getSum() / stats.getCount());
        assertEquals(stats.getMax(), 1000L);
        assertEquals(stats.getMin(), 1L);
    }
}
 
Example #6
Source File: LongSummaryStatisticsExample.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void long_summary_stats_stream_reduction_target() {

	LongSummaryStatistics stats = shipments.stream().collect(
			Collectors.summarizingLong(Shipment::getCost));

	// average
	assertEquals(310.25, stats.getAverage(), 0);

	// count
	assertEquals(4, stats.getCount(), 0);

	// max
	assertEquals(901.0, stats.getMax(), 0);

	// min
	assertEquals(45.0, stats.getMin(), 0);

	// sum
	assertEquals(1241.0, stats.getSum(), 0);
}
 
Example #7
Source File: ThreadPoolRequestReplicator.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void logTimingInfo(final AsyncClusterResponse response) {
    // Calculate min, max, mean for the requests
    final LongSummaryStatistics stats = response.getNodesInvolved().stream()
            .map(p -> response.getNodeResponse(p).getRequestDuration(TimeUnit.MILLISECONDS))
            .collect(Collectors.summarizingLong(Long::longValue));

    final StringBuilder sb = new StringBuilder();
    sb.append("Node Responses for ").append(response.getMethod()).append(" ").append(response.getURIPath()).append(" (Request ID ").append(response.getRequestIdentifier()).append("):\n");
    for (final NodeIdentifier node : response.getNodesInvolved()) {
        sb.append(node).append(": ").append(response.getNodeResponse(node).getRequestDuration(TimeUnit.MILLISECONDS)).append(" millis\n");
    }

    logger.debug("For {} {} (Request ID {}), minimum response time = {}, max = {}, average = {} ms",
            response.getMethod(), response.getURIPath(), response.getRequestIdentifier(), stats.getMin(), stats.getMax(), stats.getAverage());
    logger.debug(sb.toString());
}
 
Example #8
Source File: CollectAndSummaryStatisticsTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void testLongStatistics() {
    List<LongSummaryStatistics> instances = new ArrayList<>();
    instances.add(countTo(1000).stream().collect(Collectors.summarizingLong(i -> i)));
    instances.add(countTo(1000).stream().mapToLong(i -> i).summaryStatistics());
    instances.add(countTo(1000).stream().mapToLong(i -> i).collect(LongSummaryStatistics::new,
                                                                   LongSummaryStatistics::accept,
                                                                   LongSummaryStatistics::combine));
    instances.add(countTo(1000).parallelStream().collect(Collectors.summarizingLong(i -> i)));
    instances.add(countTo(1000).parallelStream().mapToLong(i -> i).summaryStatistics());
    instances.add(countTo(1000).parallelStream().mapToLong(i -> i).collect(LongSummaryStatistics::new,
                                                                           LongSummaryStatistics::accept,
                                                                           LongSummaryStatistics::combine));

    for (LongSummaryStatistics stats : instances) {
        assertEquals(stats.getCount(), 1000);
        assertEquals(stats.getSum(), (long) countTo(1000).stream().mapToInt(i -> i).sum());
        assertEquals(stats.getAverage(), (double) stats.getSum() / stats.getCount());
        assertEquals(stats.getMax(), 1000L);
        assertEquals(stats.getMin(), 1L);
    }
}
 
Example #9
Source File: CollectAndSummaryStatisticsTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void testLongStatistics() {
    List<LongSummaryStatistics> instances = new ArrayList<>();
    instances.add(countTo(1000).stream().collect(Collectors.summarizingLong(i -> i)));
    instances.add(countTo(1000).stream().mapToLong(i -> i).summaryStatistics());
    instances.add(countTo(1000).stream().mapToLong(i -> i).collect(LongSummaryStatistics::new,
                                                                   LongSummaryStatistics::accept,
                                                                   LongSummaryStatistics::combine));
    instances.add(countTo(1000).parallelStream().collect(Collectors.summarizingLong(i -> i)));
    instances.add(countTo(1000).parallelStream().mapToLong(i -> i).summaryStatistics());
    instances.add(countTo(1000).parallelStream().mapToLong(i -> i).collect(LongSummaryStatistics::new,
                                                                           LongSummaryStatistics::accept,
                                                                           LongSummaryStatistics::combine));

    for (LongSummaryStatistics stats : instances) {
        assertEquals(stats.getCount(), 1000);
        assertEquals(stats.getSum(), (long) countTo(1000).stream().mapToInt(i -> i).sum());
        assertEquals(stats.getAverage(), (double) stats.getSum() / stats.getCount());
        assertEquals(stats.getMax(), 1000L);
        assertEquals(stats.getMin(), 1L);
    }
}
 
Example #10
Source File: RegistryTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void timers() {
  Registry r = newRegistry(true, 10000);
  r.timer("foo").record(1L, TimeUnit.NANOSECONDS);
  r.timer("foo", "a", "1", "b", "2").record(1L, TimeUnit.NANOSECONDS);
  r.timer("foo", "a", "1", "b", "3").record(13L, TimeUnit.NANOSECONDS);
  r.timer("foo", "a", "1", "b", "2").record(1L, TimeUnit.NANOSECONDS);
  r.timer("bar", "a", "1", "b", "2").record(1L, TimeUnit.NANOSECONDS);

  Assertions.assertEquals(4, r.timers().count());

  final LongSummaryStatistics countSummary = r.timers()
      .filter(Functions.nameEquals("foo"))
      .collect(Collectors.summarizingLong(Timer::count));
  Assertions.assertEquals(3L, countSummary.getCount());
  Assertions.assertEquals(4L, countSummary.getSum());
  Assertions.assertEquals(2L, countSummary.getMax());

  final LongSummaryStatistics totalSummary = r.timers()
      .filter(Functions.nameEquals("foo"))
      .collect(Collectors.summarizingLong(Timer::totalTime));
  Assertions.assertEquals(3L, totalSummary.getCount());
  Assertions.assertEquals(16L, totalSummary.getSum());
  Assertions.assertEquals(13L, totalSummary.getMax());
}
 
Example #11
Source File: LongSummaryStatisticsTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_empty() {
    LongSummaryStatistics lss = new LongSummaryStatistics();
    assertEquals(0, lss.getCount());
    assertEquals(0, lss.getSum());
    assertEquals(0.0d, lss.getAverage());
    assertEquals(Long.MAX_VALUE, lss.getMin());
    assertEquals(Long.MIN_VALUE, lss.getMax());
}
 
Example #12
Source File: StatisticsHelper.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Map<String, String> process(List<Long> samples) {

        // aftermath
        Collections.sort(samples);

        // - average, max, min , sample size
        LongSummaryStatistics statistics = samples.stream().mapToLong(val -> val).summaryStatistics();

        Map<String, String> results = new HashMap<>();
        results.put("average", String.valueOf(Math.round(statistics.getAverage())));
        results.put("max", String.valueOf(statistics.getMax()));
        results.put("min", String.valueOf(statistics.getMin()));
        results.put("sampleSize", String.valueOf(statistics.getCount()));

        // - p25, median, p75
        Integer[] percentiles = new Integer[] { 25, 50, 75 };
        for (Integer percentile : percentiles) {
            double rank = statistics.getCount() * percentile / 100.0;
            Long percentileValue;
            if (samples.size() <= rank + 1)
                percentileValue = samples.get(samples.size() - 1);
            else if (Math.floor(rank) == rank)
                percentileValue = samples.get((int) rank);
            else
                percentileValue = Math.round(samples.get((int) Math.floor(rank))
                        + (samples.get((int) (Math.floor(rank) + 1)) - samples.get((int) Math.floor(rank)))
                                / (rank - Math.floor(rank)));
            results.put("p" + percentile, String.valueOf(percentileValue));
        }

        return results;
    }
 
Example #13
Source File: StreamUtils.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public static <T, R> void printLongStats( Stream<T> stream, ToLongFunction<T> summarizingFunction ) {
    LongSummaryStatistics summary = stream.collect(Collectors.summarizingLong(summarizingFunction));

    System.out.println(summary.getCount());
    System.out.println(summary.getSum());
    System.out.println(summary.getMin());
    System.out.println(summary.getMax());
    System.out.println(summary.getAverage());
}
 
Example #14
Source File: CollectAndSummaryStatisticsTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void testLongCollectNull() {
    checkNPE(() -> LongStream.of(1).collect(null,
                                           LongSummaryStatistics::accept,
                                           LongSummaryStatistics::combine));
    checkNPE(() -> LongStream.of(1).collect(LongSummaryStatistics::new,
                                            null,
                                            LongSummaryStatistics::combine));
    checkNPE(() -> LongStream.of(1).collect(LongSummaryStatistics::new,
                                            LongSummaryStatistics::accept,
                                            null));
}
 
Example #15
Source File: NatsStatistics.java    From nats.java with Apache License 2.0 5 votes vote down vote up
void registerSummaryStat(LongSummaryStatistics stats, long value) {
    if(!trackAdvanced) {
        return;
    }
    lock.lock();
    try {
        stats.accept(value);
    } finally {
        lock.unlock();
    }
}
 
Example #16
Source File: LongSummaryStatisticsTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_combine() {
    LongSummaryStatistics lss1 = getLongSummaryStatisticsData2();
    LongSummaryStatistics lssCombined = getLongSummaryStatisticsData1();
    lssCombined.combine(lss1);

    assertEquals(12, lssCombined.getCount());
    assertEquals(118L, lssCombined.getSum());
    assertEquals(100L, lssCombined.getMax());
    assertEquals(-5L, lssCombined.getMin());
    assertEquals(9.833333, lssCombined.getAverage(), 1E-6);
}
 
Example #17
Source File: LongSummaryStatisticsTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private static LongSummaryStatistics getLongSummaryStatisticsData2() {
    LongSummaryStatistics lss = new LongSummaryStatistics();
    for (long value : data2) {
        lss.accept(value);
    }
    return lss;
}
 
Example #18
Source File: AverageValueSizeTest.java    From Chronicle-Map with Apache License 2.0 5 votes vote down vote up
public static <V> double averageValueSize(Class<V> valueClass, Iterable<V> values) {
    try (ChronicleMap<Integer, V> testMap = ChronicleMap.of(Integer.class, valueClass)
            // doesn't matter, anyway not a single value will be written to a map
            .averageValueSize(1)
            .entries(1)
            .create()) {
        LongSummaryStatistics statistics = new LongSummaryStatistics();
        for (V value : values) {
            try (MapSegmentContext<Integer, V, ?> c = testMap.segmentContext(0)) {
                statistics.accept(c.wrapValueAsData(value).size());
            }
        }
        return statistics.getAverage();
    }
}
 
Example #19
Source File: ReplicationMetrics.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Get tha average replication lag of remote replicas in given datacenter
 * @param dcName the name of dc where remote replicas sit
 * @return the average replication lag
 */
double getAvgLagFromDc(String dcName) {
  Set<RemoteReplicaInfo> replicaInfos = remoteReplicaInfosByDc.get(dcName);
  if (replicaInfos == null || replicaInfos.isEmpty()) {
    return -1.0;
  }
  LongSummaryStatistics longSummaryStatistics =
      replicaInfos.stream().collect(Collectors.summarizingLong(RemoteReplicaInfo::getRemoteLagFromLocalInBytes));
  dcToReplicaLagStats.put(dcName, longSummaryStatistics);
  return longSummaryStatistics.getAverage();
}
 
Example #20
Source File: PeriodicWatermarking.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * This method takes marks (time + position) of active writers and finds greatest lower bound on time and 
 * least upper bound on positions and returns the watermark object composed of the two. 
 * The least upper bound computed from positions may not result in a consistent and complete stream cut. 
 * So, a positional upper bound is then converted into a stream cut by including segments from higher epoch. 
 * Also, it is possible that in an effort to fill missing range, we may end up creating an upper bound that 
 * is composed of segments from highest epoch. In next iteration, from new writer positions, we may be able to 
 * compute a tighter upper bound. But since watermark has to advance position and time, we will take the upper bound
 * of previous stream cut and new stream cut. 
 * 
 * @param scope scope
 * @param streamName stream name
 * @param context operation context
 * @param activeWriters marks for all active writers. 
 * @param previousWatermark previous watermark that was emitted. 
 * @return CompletableFuture which when completed will contain watermark to be emitted. 
 */
private CompletableFuture<Watermark> computeWatermark(String scope, String streamName, OperationContext context,
                                                      List<Map.Entry<String, WriterMark>> activeWriters, Watermark previousWatermark) {
    Watermark.WatermarkBuilder builder = Watermark.builder();
    ConcurrentHashMap<SegmentWithRange, Long> upperBound = new ConcurrentHashMap<>();
    
    // We are deliberately making two passes over writers - first to find lowest time. Second loop will convert writer 
    // positions to StreamSegmentRecord objects by retrieving ranges from store. And then perform computation on those 
    // objects. 

    LongSummaryStatistics summarized = activeWriters.stream().collect(Collectors.summarizingLong(x -> x.getValue().getTimestamp()));
    long lowerBoundOnTime = summarized.getMin();
    long upperBoundOnTime = summarized.getMax();
                
    if (lowerBoundOnTime > previousWatermark.getLowerTimeBound()) {
        CompletableFuture<List<Map<SegmentWithRange, Long>>> positionsFuture = Futures.allOfWithResults(
                activeWriters.stream().map(x -> {
                    return Futures.keysAllOfWithResults(
                            x.getValue().getPosition().entrySet().stream()
                             .collect(Collectors.toMap(y -> getSegmentWithRange(scope, streamName, context, y.getKey()),
                                     Entry::getValue)));
                }).collect(Collectors.toList()));
        log.debug("Emitting watermark for stream {}/{} with time {}", scope, streamName, lowerBoundOnTime);
        return positionsFuture.thenAccept(listOfPositions -> listOfPositions.forEach(position -> {
            // add writer positions to upperBound map. 
            addToUpperBound(position, upperBound);
        })).thenCompose(v -> computeStreamCut(scope, streamName, context, upperBound, previousWatermark)
                .thenApply(streamCut -> builder.lowerTimeBound(lowerBoundOnTime).upperTimeBound(upperBoundOnTime)
                           .streamCut(ImmutableMap.copyOf(streamCut)).build()));
    } else {
        // new time is not advanced. No watermark to be emitted. 
        return CompletableFuture.completedFuture(null);
    }
}
 
Example #21
Source File: SummaryStatisticsTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void testLongStatistics() {
    List<LongSummaryStatistics> instances = new ArrayList<>();
    instances.add(countTo(1000).stream().collect(Collectors.summarizingLong(i -> i)));
    instances.add(countTo(1000).stream().mapToLong(i -> i).summaryStatistics());
    instances.add(countTo(1000).parallelStream().collect(Collectors.summarizingLong(i -> i)));
    instances.add(countTo(1000).parallelStream().mapToLong(i -> i).summaryStatistics());

    for (LongSummaryStatistics stats : instances) {
        assertEquals(stats.getCount(), 1000);
        assertEquals(stats.getSum(), (long) countTo(1000).stream().mapToInt(i -> i).sum());
        assertEquals(stats.getMax(), 1000L);
        assertEquals(stats.getMin(), 1L);
    }
}
 
Example #22
Source File: CollectAndSummaryStatisticsTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void testLongCollectNull() {
    checkNPE(() -> LongStream.of(1).collect(null,
                                           LongSummaryStatistics::accept,
                                           LongSummaryStatistics::combine));
    checkNPE(() -> LongStream.of(1).collect(LongSummaryStatistics::new,
                                            null,
                                            LongSummaryStatistics::combine));
    checkNPE(() -> LongStream.of(1).collect(LongSummaryStatistics::new,
                                            LongSummaryStatistics::accept,
                                            null));
}
 
Example #23
Source File: SummaryStatisticsTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void testLongStatistics() {
    List<LongSummaryStatistics> instances = new ArrayList<>();
    instances.add(countTo(1000).stream().collect(Collectors.summarizingLong(i -> i)));
    instances.add(countTo(1000).stream().mapToLong(i -> i).summaryStatistics());
    instances.add(countTo(1000).parallelStream().collect(Collectors.summarizingLong(i -> i)));
    instances.add(countTo(1000).parallelStream().mapToLong(i -> i).summaryStatistics());

    for (LongSummaryStatistics stats : instances) {
        assertEquals(stats.getCount(), 1000);
        assertEquals(stats.getSum(), (long) countTo(1000).stream().mapToInt(i -> i).sum());
        assertEquals(stats.getMax(), 1000L);
        assertEquals(stats.getMin(), 1L);
    }
}
 
Example #24
Source File: AbstractQueryEngine.java    From NNAnalytics with Apache License 2.0 5 votes vote down vote up
/**
 * Produces Histogram for generic summarization. Primarily for use by SuggestionEngine where
 * obtaining sum and count is vital.
 *
 * @param inodes inodes
 * @param namingFunction function to string
 * @param dataFunction function to long
 * @return histogram of sums
 */
@Override // QueryEngine
public Map<String, LongSummaryStatistics> genericSummarizingHistogram(
    Stream<INode> inodes,
    Function<INode, String> namingFunction,
    Function<INode, Long> dataFunction) {
  return inodes.collect(
      Collectors.groupingBy(
          namingFunction, Collectors.mapping(dataFunction, Collectors.summarizingLong(i -> i))));
}
 
Example #25
Source File: CollectAndSummaryStatisticsTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void testLongCollectNull() {
    checkNPE(() -> LongStream.of(1).collect(null,
                                           LongSummaryStatistics::accept,
                                           LongSummaryStatistics::combine));
    checkNPE(() -> LongStream.of(1).collect(LongSummaryStatistics::new,
                                            null,
                                            LongSummaryStatistics::combine));
    checkNPE(() -> LongStream.of(1).collect(LongSummaryStatistics::new,
                                            LongSummaryStatistics::accept,
                                            null));
}
 
Example #26
Source File: BiCollectors.java    From mug with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link BiCollector} which applies an {@code long}-producing
 * mapping function to each input pair, and returns summary statistics
 * for the resulting values.
 *
 *
 * @since 3.2
 */
public static <K, V> BiCollector<K, V, LongSummaryStatistics> summarizingLong(
    ToLongBiFunction<? super K, ? super V> mapper) {
  requireNonNull(mapper);
  return new BiCollector<K, V, LongSummaryStatistics>() {
    @Override
    public <E> Collector<E, ?, LongSummaryStatistics> splitting(
        Function<E, K> toKey, Function<E, V> toValue) {
      return Collectors.summarizingLong(e -> mapper.applyAsLong(toKey.apply(e), toValue.apply(e)));
    }
  };
}
 
Example #27
Source File: TodoServiceStatisticsController.java    From java-microservice with MIT License 5 votes vote down vote up
@GetMapping
public ObjectNode get() {
    LongSummaryStatistics statistics = monitor.getStatistics();
    return JsonNodeFactory.instance.objectNode().
            put("average-duration", statistics.getAverage()).
            put("invocation-count", statistics.getCount()).
            put("min-duration", statistics.getMin()).
            put("max-duration", statistics.getMax());
}
 
Example #28
Source File: TaskExecutorSimulator.java    From presto with Apache License 2.0 5 votes vote down vote up
private static String formatNanos(List<Long> list)
{
    LongSummaryStatistics stats = list.stream().mapToLong(Long::new).summaryStatistics();
    return format(
            "Min: %8s  Max: %8s  Avg: %8s  Sum: %8s",
            succinctNanos(stats.getMin() == Long.MAX_VALUE ? 0 : stats.getMin()),
            succinctNanos(stats.getMax() == Long.MIN_VALUE ? 0 : stats.getMax()),
            succinctNanos((long) stats.getAverage()),
            succinctNanos(stats.getSum()));
}
 
Example #29
Source File: CollectAndSummaryStatisticsTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testLongCollectNull() {
    checkNPE(() -> LongStream.of(1).collect(null,
                                           LongSummaryStatistics::accept,
                                           LongSummaryStatistics::combine));
    checkNPE(() -> LongStream.of(1).collect(LongSummaryStatistics::new,
                                            null,
                                            LongSummaryStatistics::combine));
    checkNPE(() -> LongStream.of(1).collect(LongSummaryStatistics::new,
                                            LongSummaryStatistics::accept,
                                            null));
}
 
Example #30
Source File: LongSummary.java    From jenetics with Apache License 2.0 5 votes vote down vote up
/**
 * Return a new value object of the statistical summary, currently
 * represented by the {@code statistics} object.
 *
 * @param statistics the creating (mutable) statistics class
 * @return the statistical moments
 */
public static LongSummary of(final LongSummaryStatistics statistics) {
	return new LongSummary(
		statistics.getCount(),
		statistics.getMin(),
		statistics.getMax(),
		statistics.getSum(),
		statistics.getAverage()
	);
}