One-liner: Extracting Long Statistics From A Collection of POJOs

From a collection of objects representing method calls:


public class MethodCall {

    private String methodName;
    private int duration;

    public MethodCall(String methodName, int duration) {
        this.methodName = methodName;
        this.duration = duration;
    }

    public String getMethodName() {
        return methodName;
    }

    public int getDuration() {
        return duration;
    }
}

useful statistics data can be extracted with Collectors.summarizingLong:


import java.util.ArrayList;
import java.util.LongSummaryStatistics;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;

public class LongSummaryStatisticsTest {

    private ArrayList<MethodCall> calls;

    @Before
    public void provideTestData() {
        this.calls = new ArrayList<>();
        calls.add(new MethodCall("save", 90));
        calls.add(new MethodCall("find", 10));
        calls.add(new MethodCall("delete", 2));

    }

    @Test
    public void computeStatistics() {

        LongSummaryStatistics statistics = this.calls.stream().
                collect(Collectors.summarizingLong(MethodCall::getDuration));

        assertThat(statistics.getCount(), is(3l));
        assertThat(statistics.getMin(), is(2l));
        assertThat(statistics.getMax(), is(90l));
        assertThat(statistics.getAverage(), is(34d));
        assertThat(statistics.getSum(), is(102l));
    }

}


The code above was extracted from "Effective Java EE" online course (coming soon), the second part of the Java EE Bootstrap at parleys.com.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting


Web Apps, SPA, PWA with vanilla Java Script (ES 6+), CSS 3 and WebStandards only. As simple as possible, but not simpler. See you at: (Progressive) Web apps, Single Page Apps and WebStandards airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License