LongSummaryStatistics Example

LongSummaryStatistics is an object for collecting statistics such as count, min, max, sum, and average. Although not required, it is designed to work with streams. If you are working with ints use IntSummaryStatistics or doubles use DoubleSummaryStatistics.

Setup

class Shipment {
        
    long cost;

    public Shipment(long cost) {
        super();
        this.cost = cost;
    }

    public long getCost() {
        return cost;
    }        
}

List<Shipment> shipments;

@Before
public void setUp() {
    shipments = new ArrayList<>();
    shipments.add(new Shipment(45));
    shipments.add(new Shipment(65));
    shipments.add(new Shipment(901));
    shipments.add(new Shipment(230));
}

Java 8

Compute summary statistics on a stream

@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);
}

LongSummaryStatistics as a reduction target

@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);
}