IntSummaryStatistics Example

IntSummaryStatistics 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 longs use LongSummaryStatistics or doubles use DoubleSummaryStatistics.

Setup

class OrderEntry {

    int amount;

    public OrderEntry(int amount) {
        super();
        this.amount = amount;
    }

    public int getAmount() {
        return amount;
    }
}

List<OrderEntry> orderEntries;

@Before
public void setUp() {
    orderEntries = new ArrayList<>();
    orderEntries.add(new OrderEntry(10));
    orderEntries.add(new OrderEntry(14));
    orderEntries.add(new OrderEntry(12));
    orderEntries.add(new OrderEntry(18));
}

Java 8

Compute summary statistics on a stream

@Test
public void test_methods() {

    IntSummaryStatistics stats = orderEntries.stream()
            .mapToInt((x) -> x.getAmount()).summaryStatistics();

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

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

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

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

    // sum
    assertEquals(54, stats.getSum(), 0);
}

IntSummaryStatistics as a reduction target

@Test
public void int_summary_stats_stream_reduction_target() {

    IntSummaryStatistics stats = orderEntries.stream().collect(
            Collectors.summarizingInt(OrderEntry::getAmount));

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

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

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

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

    // sum
    assertEquals(54, stats.getSum(), 0);
}